JavaScript:上传文件纯 JS

2022-08-30 00:23:36

假设我在页面上有这个元素:

<input id="image-file" type="file" />

这将创建一个按钮,允许网页的用户通过操作系统“文件打开...”选择文件。对话框中的对话框。

假设用户单击所述按钮,在对话框中选择一个文件,然后单击“确定”按钮关闭对话框。

选定的文件名现在存储在:

document.getElementById("image-file").value

现在,假设服务器在URL“/upload/image”处处理多部分POST。

如何将文件发送到“/上传/图像”?

另外,如何侦听文件上传完成的通知?


答案 1

纯 JS

您可以选择将抓取与 await-try-catch 结合使用

let photo = document.getElementById("image-file").files[0];
let formData = new FormData();
     
formData.append("photo", photo);
fetch('/upload/image', {method: "POST", body: formData});

async function SavePhoto(inp) 
{
    let user = { name:'john', age:34 };
    let formData = new FormData();
    let photo = inp.files[0];      
         
    formData.append("photo", photo);
    formData.append("user", JSON.stringify(user)); 
    
    const ctrl = new AbortController()    // timeout
    setTimeout(() => ctrl.abort(), 5000);
    
    try {
       let r = await fetch('/upload/image', 
         {method: "POST", body: formData, signal: ctrl.signal}); 
       console.log('HTTP response code:',r.status); 
    } catch(e) {
       console.log('Huston we have problem...:', e);
    }
    
}
<input id="image-file" type="file" onchange="SavePhoto(this)" >
<br><br>
Before selecting the file open chrome console > network tab to see the request details.
<br><br>
<small>Because in this example we send request to https://stacksnippets.net/upload/image the response code will be 404 ofcourse...</small>

<br><br>
(in stack overflow snippets there is problem with error handling, however in <a href="https://jsfiddle.net/Lamik/b8ed5x3y/5/">jsfiddle version</a> for 404 errors 4xx/5xx are <a href="https://stackoverflow.com/a/33355142/860099">not throwing</a> at all but we can read response status which contains code)

老派方法 - xhr

let photo = document.getElementById("image-file").files[0];  // file from input
let req = new XMLHttpRequest();
let formData = new FormData();

formData.append("photo", photo);                                
req.open("POST", '/upload/image');
req.send(formData);

function SavePhoto(e) 
{
    let user = { name:'john', age:34 };
    let xhr = new XMLHttpRequest();
    let formData = new FormData();
    let photo = e.files[0];      
    
    formData.append("user", JSON.stringify(user));   
    formData.append("photo", photo);
    
    xhr.onreadystatechange = state => { console.log(xhr.status); } // err handling
    xhr.timeout = 5000;
    xhr.open("POST", '/upload/image'); 
    xhr.send(formData);
}
<input id="image-file" type="file" onchange="SavePhoto(this)" >
<br><br>
Choose file and open chrome console > network tab to see the request details.
<br><br>
<small>Because in this example we send request to https://stacksnippets.net/upload/image the response code will be 404 ofcourse...</small>

<br><br>
(the stack overflow snippets, has some problem with error handling - the xhr.status is zero (instead of 404) which is similar to situation when we run script from file on <a href="https://stackoverflow.com/a/10173639/860099">local disc</a> - so I provide also js fiddle version which shows proper http error code <a href="https://jsfiddle.net/Lamik/k6jtq3uh/2/">here</a>)

总结

  • 在服务器端,您可以读取原始文件名(和其他信息),这些信息会自动包含在formData参数中,由浏览器请求。filename
  • 您不需要将请求标头设置为 - 这将由浏览器自动设置(这将包括必需的边界参数)。Content-Typemultipart/form-data
  • 而不是你可以使用完整的地址,如(当然这两个地址都是任意的,取决于服务器 - 以及参数的情况相同 - 通常在服务器上“POST”用于文件上传,但有时可以使用“PUT”或其他)。/upload/imagehttp://.../upload/imagemethod
  • 如果要在单个请求中发送多个文件,请使用属性:,并以类似的方式将所有选定的文件附加到formData(例如...multiple<input multiple type=... />photo2=...files[2];formData.append("photo2", photo2);)
  • 您可以包含其他数据(json)来请求,例如 通过这种方式:let user = {name:'john', age:34}formData.append("user", JSON.stringify(user));
  • 您可以设置超时:用于使用,用于旧方法fetchAbortControllerxhr.timeout= milisec
  • 此解决方案应该适用于所有主流浏览器。

答案 2

除非您尝试使用 ajax 上传文件,否则只需将表单提交到 。/upload/image

<form enctype="multipart/form-data" action="/upload/image" method="post">
    <input id="image-file" type="file" />
</form>

如果您确实想在后台上传图像(例如,无需提交整个表单),则可以使用ajax: