2

I am trying to change a file, uploaded to form via user, before being sent to server via POST and multipart (I inactivate the button until all file is parsed fully). Is there a way to change the uploaded file ( i call it newFile below) in the form? I have tried things like this:

document.getElementById("myFormInputField").files[0] = newFile;

and change the form data for the file with:

formData.set(name, newFile, fileName)

Should any of that work?...

My solution is instead to use XMLHttpRequest like below. And convert the encoding I have in file from CP473 to UTF8 with readAsArrayBuffer with following: PC8 / CP437 character set with filereader in Chrome

function sendFile(newFile) {

  const uri = "/upload";
  const xhr = new XMLHttpRequest();
  const fd = new FormData();

  xhr.open("POST", uri, true);
  xhr.onreadystatechange = function() {
      if (xhr.readyState == 4 && xhr.status == 200) {
          alert(xhr.responseText); // handle response.
      }
  };
  fd.append('myFile', file);
  // Initiate a multipart/form-data upload
  xhr.send(fd);
}
Sturm
  • 93
  • 1
  • 7
  • 1
    You can't programmatically change a user's uploaded file that they are attempting to POST, mid-request. You can capture the request, prevent the default, and create a new request to the server with an altered file. What's wrong with the solution you are showing? – Heretic Monkey Feb 01 '21 at 19:07
  • @HereticMonkey Thanks that was really the answer I was looking for. Follow-up question - could I use InputStreamReader? It seams to be require some imported modules? It looks like it have CP437 encoding included in the package. My manual encoding coversion above makes it take 4 times longer.. – Sturm Feb 01 '21 at 23:47

0 Answers0