【SpringBoot与Vue实现文件上传】 MultipartFile与SysLog冲突(大坑)

html

这里用的组件是 ant-design-vue

<a-input type="file" @change="upload_photo($event)" accept="image/*"></a-input>

js

       //input触发事件
       upload_photo: function(e){
        let file = e.target.files[0];
        console.log(file);

        this.uploadFile(file);

       },

      //图片上传
      uploadFile(file){

        let httpurl = this.url.uploadFile;  //后端接口地址
        var formData = new FormData();
        formData.append('file',file);

        axios.post(httpurl,formData).then((response) => {
          console.log('响应');
          console.log(response);
          this.$message.success('成功');
        }).catch(function (err) {
          console.log('失败');
          console.log(err);    //捕获异常
          this.$message.warning('失败');
        }).finally(()=>{

        });

      },

后端 controller

@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
	 public Map<String, String> uploadPhoto(MultipartFile file, HttpServletRequest request) throws IOException, ServletException {
	 	 Map<String, String> ret = new HashMap<String, String>();
		 logger.info("getName = "+file.getName());
		 logger.info("getOriginalFilename = "+file.getOriginalFilename());
		 ret.put("type", "success");
		 return ret;
	 }

运行之后后端确实能接收到了文件,文件名和原文件名都打印出来了,但是报错,抛出了异常

Caused by: com.alibaba.fastjson.JSONException: write javaBean error, fastjson version 1.2.60, class org.springframework.web.multipart.MultipartFileResource, fieldName : resource
	at com.alibaba.fastjson.serializer.JavaBeanSerializer.write(JavaBeanSerializer.java:525)
	at com.alibaba.fastjson.serializer.JavaBeanSerializer.write(JavaBeanSerializer.java:160)
	at com.alibaba.fastjson.serializer.FieldSerializer.writeValue(FieldSerializer.java:325)
	at com.alibaba.fastjson.serializer.JavaBeanSerializer.write(JavaBeanSerializer.java:456)
	... 110 common frames omitted
Caused by: java.io.FileNotFoundException: MultipartFile resource [photo] cannot be resolved to absolute file path
	at org.springframework.core.io.AbstractResource.getFile(AbstractResource.java:124)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
	at com.alibaba.fastjson.util.FieldInfo.get(FieldInfo.java:491)
	at com.alibaba.fastjson.serializer.FieldSerializer.getPropertyValueDirect(FieldSerializer.java:150)
	at com.alibaba.fastjson.serializer.JavaBeanSerializer.write(JavaBeanSerializer.java:293)
	... 113 common frames omitted

一个是

Caused by: com.alibaba.fastjson.JSONException: write javaBean error, fastjson version 1.2.60, class org.springframework.web.multipart.MultipartFileResource, fieldName : resource

另一个是

Caused by: java.io.FileNotFoundException: MultipartFile resource [photo] cannot be resolved to absolute file path

意思是json工具序列化失败了,然后和MultipartFile有关,

我在网上找了一下相关问题,发现了这个 https://github.com/alibaba/fastjson/issues/3505

1、fastjson在打印JSON字符串时,会通过反射得到一个object的所有getter方法,然后取其值,最后拼装成一个JSON字符串。

2、MultipartFile对象有一个 Resource getResource() 方法

3、fastjson在得到Resource后,会继续对Resource对象进行遍历

4、Resource是一个接口,其中有个 getFile 方法,MultipartFileResource本身并没有对 getFile 进行重写

那是什么东西触发了fastjson去序列化MultipartFile呢?是日志框架syslog

解决

既然MultipartFile会被强行序列化,那我们只要设置MultipartFile跳过序列化就行了,这里我们可以用 @JSONField(serialize = false) 修饰

但是直接用来修饰参数不会生效,所以需要给MultipartFile封装一层

public class MyFile {
    @JSONField(serialize = false)
    private MultipartFile file;

    public MultipartFile getFile() {
        return file;
    }

    public void setFile(MultipartFile file) {
        this.file = file;
    }
}
	 @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
	 public Map<String, String> uploadPhoto(MyFile file, HttpServletRequest request) throws IOException, ServletException {
	 	 Map<String, String> ret = new HashMap<String, String>();
		 logger.info("getName = "+file.getFile().getName());
		 logger.info("getOriginalFilename = "+file.getFile().getOriginalFilename());
		 ret.put("type", "success");
		 return ret;
	 }
 

--------------------------------------------------------------------------分割线---------------------------------------------------------------------------------------

关于在js中获取<input type="file">的值

<input type="file">

中是不能使用v-model双向绑定的,所以想在js中获取该input的值,需要操作操作DOM

在JavaScript中需要通过document.querySelector("#demo")来获取dom节点,然后再获取这个节点的值。在Vue中,我们不用获取dom节点,元素绑定ref之后,直接通过this.$refs即可调用,这样可以减少获取dom节点的消耗。

摘自:Vue中ref和$refs的介绍及使用_越努力,越幸运!-CSDN博客

例如:

<input type="file" ref="picture" accept="image/*">

在 vue.js 中

      var inputDOM = this.$refs.picture;
      var file = inputDOM.files;
      console.log(file[0]);  //文件内容

  • 3
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
<h3>回答1:</h3><br/>如何实现SpringBoot+Vue文件上传文件上传涉及前端和后端两个方面的实现。 前端的Vue代码: 1. 定义上传文件的模板: ``` <template> <div> <input type="file" @change="handleFileUpload" ref="fileUpload"> <button @click="submitFile">上传文件</button> </div> </template> ``` 2. 在Vue的methods中添加上传文件的方法: ``` methods: { handleFileUpload () { this.file = this.$refs.fileUpload.files[0] }, submitFile () { let formData = new FormData() formData.append('file', this.file) axios.post('/api/upload', formData, { headers: { 'Content-Type': 'multipart/form-data' } }) .then(response => { console.log(response.data) }) } } ``` 这个方法中,我们通过FormData对象来将文件对象上传到服务器端。需要注意的是,在axios请求中,我们需要指定Content-Type为multipart/form-data,以便后端能够正确地解析上传的文件。 后端的SpringBoot代码: 1. 配置文件上传Multipart配置 在application.properties文件中添加以下配置: ``` spring.servlet.multipart.max-file-size=10MB spring.servlet.multipart.max-request-size=10MB ``` 这个配置指定了上传文件的大小限制,例如,上限设置为10MB。 2. 添加文件上传的Controller ``` @RestController @RequestMapping("/api") public class FileUploadController { @PostMapping("/upload") public String uploadFile(@RequestParam("file") MultipartFile file) { try { // 将上传的文件保存到指定路径下 String filePath = "C:/uploads/" + file.getOriginalFilename(); file.transferTo(new File(filePath)); return "文件上传成功"; } catch (IOException e) { e.printStackTrace(); return "文件上传失败"; } } } ``` 这个Controller中,通过@RequestParam注解来指定上传的文件参数名,再通过MultipartFile来获取上传的文件。最后,将文件保存到指定的路径下。需要注意的是,保存路径需要在业务中合理设置。 至此,SpringBoot+Vue文件上传实现就完成了。 <h3>回答2:</h3><br/>Spring Boot是一个广受欢迎的Java开发框架,Vue是一款流行的前端开发框架,他们之间的结合可以为用户提供高效、易用的Web应用程序。在其中,文件上传Web应用程序的必备功能之一。Spring BootVue的结合可使文件上传实现更加轻松快捷。 首先,需要在前端部分使用Vue来创建一个简单的文件上传组件,该组件可以实现文件选择、文件上传以及进度条的显示等功能。可以使用vue-file-upload或者其他类似的第三方库来实现文件上传功能,同时需要在该组件中设置上传API的路径和上传的文件名。 然后,需要在后端部分使用Spring Boot来处理上传的文件。Spring Boot提供了丰富的文件处理工具和API,可以轻松地实现文件上传。可以使用Spring BootMultipartResolver来解析文件上传请求,同时可以使用MultipartFile类来获取上传的文件对象。 接着,需要在Spring Boot的Controller中创建一个上传接口用于处理文件上传请求。该接口需要使用@RequestParam注解来获取上传的文件对象,并使用MultipartFile类来处理文件上传。同时,还需要设置上传文件的路径,并将上传成功后的文件路径返回到前端。 最后,需要在前端页面使用Vue来处理上传结果。根据上传返回的结果,可以在页面上显示上传成功或者上传失败的提示信息。同时,还可以使用Vue实现进度条的动态更新,用以提醒用户当前的上传状态。 总的来说,Spring BootVue的结合可以实现快速、高效的文件上传功能。借助两个框架提供的强大工具和API,开发者可以轻松地实现文件上传功能,提高Web应用程序的可靠性和用户体验。 <h3>回答3:</h3><br/>SpringBoot是一个基于Spring框架的快速开发微服务的工具,它简化了Spring框架的配置,使开发者可以快速上手。Vue是一款流行的前端框架,它具有高效的组件化开发和数据双向绑定等优点。在实现文件上传功能时,可以结合使用SpringBootVue实现。 首先,需要在SpringBoot的依赖管理文件pom.xml中添加对spring-boot-starter-webspring-boot-starter-test的引用: ``` <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> ``` 然后,在SpringBoot的配置文件application.properties中添加文件上传的配置: ``` spring.servlet.multipart.enabled=true spring.servlet.multipart.max-file-size=200MB spring.servlet.multipart.max-request-size=215MB ``` 接下来,在SpringBoot的Controller中编写文件上传接口: ``` @RestController @RequestMapping("/api") @CrossOrigin(origins = "*", maxAge = 3600) public class UploadController { @PostMapping("/upload") public ResponseResult upload(@RequestParam("file") MultipartFile file) { // 处理文件上传业务逻辑 } } ``` 在Vue的组件中,可以使用vue-axios实现文件上传: ``` <template> <div> <input type="file" @change="uploadFile" /> </div> </template> <script> import axios from 'axios'; export default { data() { return { file: null } }, methods: { uploadFile() { let formData = new FormData(); formData.append('file', this.file); axios.post('http://localhost:8080/api/upload', formData, { headers: { 'Content-Type': 'multipart/form-data' } }) .then(res => { console.log(res.data); }) .catch(error => { console.log(error); }) } } } </script> ``` 其中,formData为提交的表单数据,append方法将文件对象添加到表单中。axios.post方法发送POST请求,在请求头中设置Content-Type为multipart/form-data。 总体来说,使用SpringBootVue实现文件上传功能比较简单。通过配置SpringBoot文件上传参数和编写文件上传接口,配合Vue文件上传组件,即可实现文件的上传功能。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值