如何使用javascript上传文件?

8

我想使用JavaScript创建一个上传器。有人可以帮助我学习如何使用JavaScript上传文件吗?


1
除非你自己先帮助自己,否则我们无法帮助你。请贴出你尝试过的代码。 - Krishna Prashatt
1
可能重复于https://dev59.com/2m035IYBdhLWcg3wKsqa#5587986 - Terry Wei
可能是重复的问题:JavaScript:上传文件 - JJJ
3个回答

13

我想上传一个文件而不使用php。我只是想知道,我能否使用js上传文件? - Manjeet Kumar Nai

7
你可以使用 XMLHttpRequestFormData 上传文件。下面的示例展示了如何上传新选择的文件。
<input type="file" name="my_files[]" multiple/>
<script>
const input = document.querySelector('input[type="file"]');
input.addEventListener('change', (e) => {

  const fd = new FormData();

  // add all selected files
  e.target.files.forEach((file) => {
    fd.append(e.target.name, file, file.name);  
  });
  
  // create the request
  const xhr = new XMLHttpRequest();
  xhr.onload = () => {
    if (xhr.status >= 200 && xhr.status < 300) {
        // we done!
    }
  };
  
  // path to server would be where you'd normally post the form to
  xhr.open('POST', '/path/to/server', true);
  xhr.send(fd);
});
</script>

我喜欢 MDN 的示例,但我认为 MDN 上关于这个的示例可能已经过时了。你能确认一下你所描述的方法是否有效吗?我正在使用 formData.append(),和你一样,它可以上传文件。MDN 上的示例是手动创建表单数据的。https://developer.mozilla.org/en-US/docs/Learn/Forms/Sending_forms_through_JavaScript#dealing_with_binary_data - 1.21 gigawatts
我喜欢 MDN 的示例,但我认为 MDN 上关于这个的示例可能已经过时了。你能确认一下你所描述的方法是否有效吗?我正在使用 formData.append(),和你一样,它可以上传文件。MDN 上的示例是手动创建表单数据的。https://developer.mozilla.org/en-US/docs/Learn/Forms/Sending_forms_through_JavaScript#dealing_with_binary_data - undefined
获取错误:e.target.files.forEach不是一个函数。 - undefined

0

HTML部分:

<form enctype = "multipart/form-data" onsubmit="return false;" >
       <input id="file" type="file" name="static_file" />
       <button id="upload-button" onclick="uploadFile(this.form)"> Upload </button>
    </form>

JavaScript 部分:

function uploadFile(form){
     const formData = new FormData(form);
     var oOutput = document.getElementById("static_file_response")
     var oReq = new XMLHttpRequest();
         oReq.open("POST", "upload_static_file", true);
     oReq.onload = function(oEvent) {
         if (oReq.status == 200) {
           oOutput.innerHTML = "Uploaded!";
           console.log(oReq.response)
         } else {
           oOutput.innerHTML = "Error occurred when trying to upload your file.<br \/>";
         }
         };
     oOutput.innerHTML = "Sending file!";
     console.log("Sending file!")
     oReq.send(formData);
    }

在上面的 HTML 中,我使用表单来捕获文件,并在按钮被点击时调用 JS 函数。在 JS 函数中,我使用 XMLHttpRequest 来发送文件。
可以在此处找到详细的逐步文档here

{ "message": "未捕获的引用错误:uploadFile未定义", "filename": "https://stacksnippets.net/js", "lineno": 12, "colno": 67 } - Boris Gafurov

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接