Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

axios 怎么在Post请求中,同时传递文件和对象

addAppVersion(formdata: any, file: any) {
    const data = new FormData();
    data.append('appfile', file);
    data.append('appVersion', JSON.stringify(formdata));
    //Object.entries(formdata).forEach((arr: [string,any]) => {data.append(arr[0], arr[1]);})
    return new Promise((resolve: Function,reject: Function) => {
      axios({
        url:'/app/versionManager/addAppVersion',
        method:'post',
        headers: {
          'Content-Type': 'multipart/form-data',
        },
        data: data
      }).then((res: any) => {
        resolve(res.data)
      }).catch((err: any) => {
        reject(err)
      });
    })

formData.append(name, value) 表单的值。USVStringBlob (包括子类型,如 File)。所以上述的date需要被JSON.stringify,才能存入FormData字符串。我这里想在请求前进行appVersion值的反序列化,但是尝试使用transformRequest和拦截器都失败了。

这样请求的参数appVersion是一个JSON字符串,能不能做到直接传递一个对象参数呢?或者用其他方式传递file?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

image.png

传入一个 FormDatamultipart/form-data),却序列化成了 JSONapplication/json),最后又强行指定数据类型是键值对application/x-www-form-urlencoded)???

这是什么奇葩的写法???

为啥不直接用 FormData 往上传???


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...