0

Assuming I have a file data.txt and I want to send it using POST with XHR.

I found this. All my google searches have led to the use of FormData object.

<input type="file" id="uploadfile" name="uploadfile" />
<input type="button" value="upload" onclick="upload()" />

<script>
var client = new XMLHttpRequest();

function upload() 
{
  var file = document.getElementById("uploadfile");

  /* Create a FormData instance */
  var formData = new FormData();
  /* Add the file */ 
  formData.append("upload", file.files[0]);

  client.open("post", "/upload", true);
  client.setRequestHeader("Content-Type", "multipart/form-data");
  client.send(formData);  /* Send to server */ 
}

/* Check the response status */  
client.onreadystatechange = function() 
{
  if (client.readyState == 4 && client.status == 200) 
  {
     alert(client.statusText);
  }
}
</script>

This example looks nice however I want the file to be uploaded without the pick of it which isn't the case in this code.

So I thought about putting a custom value in the file input like this :

<input value = "data.txt" type="file" id="uploadfile" name="uploadfile" />

But apparently we just can't do it.

So how can I achieve this with or without using FormData knowing that I want to send this file without picking it ?

Community
  • 1
  • 1
  • 1
    Imagine anyone being able to select any file to upload off your computer.It can't be done. – epascarello Apr 21 '15 at 17:57
  • Really so I can only upload files that I pick myself ? – user181716 Apr 21 '15 at 17:59
  • Wouldn't this be a massive security violation? I could write a website that sends random files to the server – beautifulcoder Apr 21 '15 at 18:01
  • @user181716 Yes. That's the idea. Otherwise it would raise a big security issues. – anu Apr 21 '15 at 18:01
  • You can try creating a script that runs without the browser. What you are trying to achieve is blocked by browsers for web security reasons. It's the same reason you can't get the full local path of a file from `'. – boombox Apr 21 '15 at 18:09

1 Answers1

0

What you're asking is not possible for very obvious security reasons.

Imagine a website that could just grab any file it wanted from your machine and upload it to its server without any interaction or authorisation on your part.

What you can do, though, to go some way towards ensuring the correct file is uploaded is add a server side check that the name of the file being uploaded is data.txt before processing.

Shaggy
  • 6,696
  • 2
  • 25
  • 45