问题
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)
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--
But I need this,
------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--
Here is my code:
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:
I found the sources of my errors
- I only needed
FormData()
- it takes care of the file and hidden fields. - I was overwriting
Content-Type
. Form boundaries were lost when I did this:
`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);
}
})
来源:https://stackoverflow.com/questions/43245657/how-do-i-append-a-file-to-formdata