Java中將File轉化為MultipartFile的操作
話不多說直接上代碼,簡單明了
import java.io.File;import java.io.FileInputStream;import org.springframework.web.multipart.MultipartFile;import org.springframework.mock.web.MockMultipartFile;import org.apache.http.entity.ContentType; File pdfFile = new File('D://test.pdf');FileInputStream fileInputStream = new FileInputStream(pdfFile);MultipartFile multipartFile = new MockMultipartFile(pdfFile.getName(), pdfFile.getName(), ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);
不少網友反饋說要下jar包的依賴,如下
jar包依賴:
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpcore</artifactId> <version>4.4.9</version></dependency><dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>5.1.6.RELEASE</version></dependency>
補充知識:SPRING MVC文件上傳功能關于不能實例化MultipartFile對象原因分析
實現文件上傳有幾個需要注意的地方
1、文件上傳的HTML,需要在form中加入enctype='multipart/form-data'
2、在Spring的配置文件中需要指定org.springframework.web.multipart.commons.CommonsMultipartResolver。
<bean class='org.springframework.web.multipart.commons.CommonsMultipartResolver'> <property name='defaultEncoding' value='UTF-8' /> <!-- 指定所上傳文件的總大小,單位字節。注意maxUploadSize屬性的限制不是針對單個文件,而是所有文件的容量之和 --> <property name='maxUploadSize' value='10240000' /> </bean>
3、在我們執行文件上傳方法的Controller類上面需要加入@RequestParam注解或在Spring的配置文件中加入<mvc:annotation-driven/>的配置
@RequestMapping('upload.do') public String upload(@RequestParam MultipartFile file) {<mvc:annotation-driven/>
如果在我們不加入@RequestParam注解且沒有加入<mvc:annotation-driven/>注解的情況下,在執行文件上傳時會報如下異常:
javax.servlet.ServletException: org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.multipart.MultipartFile]: Specified class is an interface at org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:146) at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:132) at org.eclipse.jetty.server.Server.handle(Server.java:531) at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:352) at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:260) at org.eclipse.jetty.io.AbstractConnection$ReadCallback.succeeded(AbstractConnection.java:281) at org.eclipse.jetty.io.FillInterest.fillable(FillInterest.java:102) at org.eclipse.jetty.io.ChannelEndPoint$2.run(ChannelEndPoint.java:118) at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:760) at org.eclipse.jetty.util.thread.QueuedThreadPool$2.run(QueuedThreadPool.java:678) at java.lang.Thread.run(Thread.java:745)
注:個人比較建議在配置文件中加入annotation-driven用于打開注解驅動。這樣我們在做文件上傳時,就不需要在每個上傳的文件對象上加入@RequestParam的注解了。
以上這篇Java中將File轉化為MultipartFile的操作就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持好吧啦網。
相關文章:
