vue2+axios上传图片后台接收不到

1.我想实现vue前端上传图片的功能,后台使用Java实现

@RequestMapping(value = "uploadDeliveryImg.json", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject uploadDeliveryImg(@RequestParam MultipartFile file, HttpServletResponse response, HttpServletRequest request) {
       
        JSONObject returnMsg = new JSONObject();
        String result=null;
        try {
        // 处理逻辑

        } catch (Exception e) {
        }
        return returnMsg;
    }

postman成功接通
clipboard.png
后台也是看到了,
clipboard.png
但是我用axios请求一直进不来,这是后台报的错,网上查了一下,也没有具体的可行方案

clipboard.png
后面我换了一个jQuery库,使用ajax也是成功的。
所以我怀疑是我配置的问题,下面贴出测试代码,有经验的看下
前端

<form method="post" action="/ecp/peiapi/uploadDeliveryImg.json" @submit.prevent="comfirmAction" id="fileForm" enctype="multipart/form-data">
<input type="file" @change="getFile" name="uploadFile">
<input type="submit" value="提交">
  </form>

js

import axios from 'axios';

  export default {
    data() {
      return {
        file: {}
      };
    },
    created() {
    },
    methods: {
      getFile(e){
        console.log("e",e)
        this.file=e.target.files[0];
      },
      comfirmAction(){
        var formData = new FormData();
        formData.append('dispatchLineId', 1)
        formData.append('orderNo', 1)
        formData.append('dispatchState', 1)
        formData.append('file', this.file)
        formData.append('chunk', '0')
        let config = {
          headers: {'Content-Type': 'multipart/form-data'}
        }
        // 添加请求头
        axios.post('ecp/peiapi/uploadDeliveryImg.json', formData, config)
          .then(response => {
            if (response.data.code === 0) {
              self.ImgUrl = response.data.data
            }
            console.log(response.data)
          })
        console.log('formData.get(\'file\')=',formData.get('file'))

        axios.interceptors.request.use((config) => {
          return config;
        },(error) =>{
          return Promise.reject(error);
        });

      }
    }

网上还有人说axios request payload默认是json,但是我设了header难道没有作用吗?

阅读 13k
5 个回答

首先,谢谢各位热心的程序员。问题解决了,其实就是少了一个属性,网上说的那些都是错的,加header这个被他害苦了,希望有遇到问题的时候多去看官方文档,或者源码,共勉。
withCredentials: false, // default 改为true就行了。
下面是具体的解决代码

getFile(e){
    console.log("e",e)
    this.file=e.target.files[0];
  },
  comfirmAction(){
    var formData = new FormData();
    formData.append('file', this.file)
    const instance=axios.create({
      withCredentials: true
    })
    instance.post('ecp/peiapi/uploadDeliveryImg.json', formData)
    .then(response => {
      console.log(response.data)
    })
  }
新手上路,请多包涵

前端代码没什么问题啊,可能是我太菜了看不出哪里有问题Ծ ̮ Ծ

comfirmAction() 这个函数里 console.log(this.file) 看一下有没有值

把头的设置去掉试试

你把请求头去掉试试。
按说axios里会对数据类型做判断,是formdata的话会放弃设置请求头,改由浏览器设置。
你自己设置的话不知道会不会少一个叫boundary的东西我不太清楚。
你贴下你的请求头。
图片描述
你问题评论里补充的东西应该就是提示缺少它。


axios源码里有这个,所以对于formData数据是不需要设置header的应该。

if (utils.isFormData(requestData)) {
  delete requestHeaders['Content-Type']; // Let the browser set it
}
推荐问题