如何将文件追加到FormData

如何将文件追加到FormData

本文介绍了如何将文件追加到FormData()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

fd.append("upload", file)产量

fd.append("upload", file) yields,

------WebKitFormBoundaryJnjpATRkxe2Duwwu
Content-Disposition: form-data; name="userid"

8022171621665209152
------WebKitFormBoundaryJnjpATRkxe2Duwwu
Content-Disposition: form-data; name="upload"; filename="sample.csv"
Content-Type: text/csv


------WebKitFormBoundaryJnjpATRkxe2Duwwu--

fd.append("upload", evt.target.result)产量

fd.append("upload", evt.target.result) yields,

------WebKitFormBoundaryITfVxS7FbNWfk3Ty
Content-Disposition: form-data; name="userid"

8022171621665209152
------WebKitFormBoundaryITfVxS7FbNWfk3Ty
Content-Disposition: form-data; name="upload"

"Healthy1.jpg","1","3","1","5"
"Unhealthy1.jpg","0","2","1","2"
"Water1.jpg","2","2","1","3"
------WebKitFormBoundaryITfVxS7FbNWfk3Ty--

但是我需要这个,

------WebKitFormBoundaryITfVxS7FbNWfk3Ty
Content-Disposition: form-data; name="userid"

8022171621665209152
------WebKitFormBoundaryITfVxS7FbNWfk3Ty
Content-Disposition: form-data; name="upload"; filename="sample.csv"
Content-Type: text/csv

"Healthy1.jpg","1","3","1","5"
"Unhealthy1.jpg","0","2","1","2"
"Water1.jpg","2","2","1","3"
------WebKitFormBoundaryITfVxS7FbNWfk3Ty--

这是我的代码:

app.ports.uploadFile.subscribe(function(userid){
    var file = document.getElementById("csv").files[0];
    var fr = new FileReader();
    fr.readAsText(file, "UTF-8");
    fr.onload = function (evt) {
        console.log(evt.target.result);
        var fd = new FormData();
        fd.append("userid", userid)
        fd.append("upload", file) // <<<<< WHAT DO I PUT HERE?
        var xhr = new XMLHttpRequest()
        xhr.open('post', "http://localhost:8668/upload/ugimgset", true)
        xhr.setRequestHeader("Content-Type", "multipart/form-data")
        xhr.setRequestHeader("Authorization", "Bearer " + token() )
        xhr.send(fd)
    }
})

推荐答案

我找到了错误的来源

  1. 我只需要FormData()-它会处理文件和隐藏字段.
  2. 我正在覆盖Content-Type.当我这样做时,表单边界丢失了:
  1. I only needed FormData() - it takes care of the file and hidden fields.
  2. I was overwriting Content-Type. Form boundaries were lost when I did this:

`xhr.setRequestHeader("Content-Type","multipart/form-data")

`xhr.setRequestHeader("Content-Type", "multipart/form-data")

更正后的代码在下面(以及某些上下文):

The corrected code is below (along with some context):

app.ports.uploadFile.subscribe(function(pathAndId){
    var [tasksrvPath, formId] = pathAndId
    try {
        var fd = new FormData(document.getElementById(formId));
        var r = new XMLHttpRequest()
        r.open("POST", tasksrvPath, true)
        r.setRequestHeader("Authorization", "Bearer " + token() )
        r.send(fd)
        r.onload = function() {
            app.ports.status.send(r.statusText)
        }
    } catch(e) {
        console.log(e.message);
    }
})

这篇关于如何将文件追加到FormData()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 21:19