java字节转化为file对象_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包依赖:

org.apache.httpcomponents

httpcore

4.4.9

org.springframework

spring-test

5.1.6.RELEASE

补充知识:SPRING MVC文件上传功能关于不能实例化MultipartFile对象原因分析

实现文件上传有几个需要注意的地方

1、文件上传的HTML,需要在form中加入enctype="multipart/form-data"

2、在Spring的配置文件中需要指定org.springframework.web.multipart.commons.CommonsMultipartResolver。

class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

3、在我们执行文件上传方法的Controller类上面需要加入@RequestParam注解或在Spring的配置文件中加入的配置

@RequestMapping("upload.do")

public String upload(@RequestParam MultipartFile file) {

如果在我们不加入@RequestParam注解且没有加入注解的情况下,在执行文件上传时会报如下异常:

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的操作就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值