简体   繁体   English

Javascript:如何上传文件 onsubmit()?

[英]Javascript: How to upload file onsubmit()?

I have a JSP page with <form> that uploads a file on submit.我有一个带有<form>的 JSP 页面,该页面在提交时上传文件。 But the upload function is not uploading any file to the server at the path /uploads .但是上传function 没有将任何文件上传到路径/uploads的服务器。

HTML form: HTML 形式:

<form action="./index.jsp" onsubmit="uploadFile()">
        <input type="file" class="form-control-file " placeholder="Choose file" id="excelInput">
        <button type="submit" class="btn btn-primary">Run Profiling</button>
 </form>

Javascript function to upload file: Javascript function 上传文件:

<script>
  function uploadFile(){
      let excel = document.getElementById("excelInput").files[0];  // file from input
      alert(excel);
      let req = new XMLHttpRequest();
      let formData = new FormData();
        try{
              formData.append("excel", excel);                                
              req.open("POST", 'D:\\eclipse\\workspace\\Project2\\WebContent\\uploads');
              req.send(formData);
        }
        catch(e){ 
            alert(e);
        }
  }
  </script>

It is not going to the catch() section.它不会进入catch()部分。 But it isn't uploading either.但它也没有上传。
Is there anything missing?有什么遗漏吗?

The dupes seems to be very poor, so I post an answer.骗子似乎很穷,所以我发布了一个答案。

You basically want to add an eventListener AND submit to a WEB SERVICE!您基本上想添加一个 eventListener 并提交到 WEB SERVICE! Not a file location不是文件位置

window.addEventListener("load", function() {
  document.getElementById("uploadForm").addEventListener("submit", function(e) {
    e.preventDefault(); // stop the submit

    let excel = document.getElementById("excelInput").files[0]; // file from input

    let req = new XMLHttpRequest();
    let formData = new FormData();
    try {
      formData.append("excel", excel);
      req.open("POST", 'actual web address of a process that can handle xmlhttprequests');
      req.send(formData);
    } catch (e) {
      console.log(e);
    }
  })
})
<form action="./index.jsp" id="uploadForm">
  <input type="file" class="form-control-file " placeholder="Choose file" id="excelInput">
  <button type="submit" class="btn btn-primary">Run Profiling</button>
</form>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM