w3schools log formdata form data array javascript xmlhttprequest multipartform-data filereader form-data

javascript - log - ¿Cómo añado un archivo a FormData()?



formdata() javascript (1)

Encontré las fuentes de mis errores

  1. Solo necesitaba FormData() - se ocupa del archivo y los campos ocultos.
  2. Estaba sobrescribiendo Content-Type . Los límites de forma se perdieron cuando hice esto:

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

El código corregido está debajo (junto con algún contexto):

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); } })

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

------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) cede,

------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--

Pero necesito esto,

------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--

Aquí está mi código:

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) } })