最近作一個上傳圖片接口,以前是把圖片二進制流轉成 base64 字符串上傳,這樣傳輸量會比直接傳二進制大很多。因此就想着直接傳二進制流。java
網上有不少方法,但本身能走通的就只有兩種,一種是直接獲取 request 中的IO流,從裏面取二進制流就行。但若是傳多個文件時,上傳與接收端要區分文件很麻煩。web
另一種就比較方便(使用MultipartHttpServletRequest):spring
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; Map<String, MultipartFile> fileMap = multipartRequest.getFileMap(); for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) { MultipartFile mf = entity.getValue(); byte[] byteArray = mf.getBytes(); // 二進制流 String realName = mf.getOriginalFilename(); // 文件名 String fileExt = realName.substring(realName.lastIndexOf(".") + 1); String name = realName.substring(0, realName.indexOf(fileExt) - 1 ); // ...... }
因爲默認狀況下 request 是 HttpServletRequest 類型而不是 MultipartHttpServletRequest ,所以直接強轉會報錯。還要配置一下 xml 將 HttpServletRequest 轉成 MultipartHttpServletRequest 類型:post
<!-- make sure: MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="defaultEncoding" value="UTF-8"></property> <property name="maxUploadSize" value="50000000"></property> <property name="maxInMemorySize" value="4096"></property> </bean>
pom.xml 也要加:spa
<!-- https://mvnrepository.com/artifact/commons-io/commons-io --> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>1.4</version> </dependency> <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency>
想了解原理,能夠看看code
org.springframework.web.servlet.DispatcherServletorm
裏的代碼:
private MultipartResolver multipartResolver; // 就是由這個接口把 HttpServletRequest 轉成其它類型的xml
而 xml 中引用的 CommonsMultipartResolver 實現了 MultipartResolver 接口。所以能夠知道是由接口
CommonsMultipartResolver 把普通的 HttpServletRequest 轉成了 MultipartHttpServletRequest。圖片
postman 則要使用 form-data模式上傳圖片:
注意文件必須前面給一個字段名,如圖: image