【问题标题】:Upload mutiple files to server using Ajax call使用 Ajax 调用将多个文件上传到服务器
【发布时间】:2018-03-22 20:16:43
【问题描述】:

我有一个关于使用 Servlet 和 Ajax 调用将多个文件上传到服务器的问题。网上也有我的问题类似的问题,但我无法解决我的问题。因此,如果问题很简单或非常明显,我提前道歉。 我在表单 HTML 标记中有两个输入文件。用户可以使用文件系统浏览文件,然后点击按钮上传它们。 这是HTML代码

<form id="uploadFile">
        <input id="file1" class="files" type="file" name="file"></input>
        <input id="file2" class="files" type="file" ></input>
        <input id="processData" class="btn btn-primary" type="submit" name="submit" value="Process Data Sources" />
</form>

这是我的js代码

  //form Submit
      $("form").submit(function(evt){    
         evt.preventDefault();
         var formData = new FormData($(this)[0]);// I guess this value has to change to provide me with information of two files, but I am not sure how this can be done. 
         $.ajax({
           url: 'UploadServlet',
           type: 'POST',
           data: formData,
           async: true,
           cache: false,
           contentType: false,
           enctype: 'multipart/form-data',
           processData: false,
           success: function (response) {
             alert(response);
             console.log(response);
           }
       });
       return false;
     });

ajax 代码目前上传一个文件,但我想上传两个使用 2 个输入文件选择的文件。我不确定我该怎么做。

我从这里读到的猜测是我需要在提交函数中修改 formData 变量。 如果有人能给我提示,我真的很感激

【问题讨论】:

  • 你没有说明你遇到了什么问题
  • @Musa,对不起,我只是更新了这个问题。我的问题是如何将 2 个文件上传到服务器。 Ajax 代码目前只提交一个文件。但我想向服务器发送 2 个文件。
  • 我认为你应该阅读stackoverflow.com/questions/2422468/… - 有一部分解释了多文件上传。

标签: jquery file-upload


【解决方案1】:

您的一个文件输入缺少 name 属性

<form id="uploadFile">
        <input id="file1" class="files" type="file" name="file"> 
        <input id="file2" class="files" type="file" name="anotherfile"> 
        <input id="processData" class="btn btn-primary" type="submit" name="submit" value="Process Data Sources" />
</form>

【讨论】:

  • 感谢您提及,但我认为这不是处理多文件上传的部分。我的问题是如何修改我的 ajax 代码以上传 2 个文件,一个来自输入 id="file1",另一个来自另一个输入文件 id="file2"。
  • 如果您希望通过将表单传递给 FormData 构造函数来上传,则需要在输入字段上具有 name 属性。
猜你喜欢
  • 2016-09-07
  • 1970-01-01
  • 1970-01-01
  • 2014-04-20
  • 1970-01-01
  • 2011-10-06
  • 1970-01-01
  • 1970-01-01
  • 2014-05-26
相关资源
最近更新 更多