提问者:小点点

使用ajax上传文件并使用Java servlet服务器端处理


我在过去几天里一直被困在这个问题上,没有其他的帖子对我有帮助。 我正在尝试在一个HTML表单上上传一个文件,该表单看起来像这样(它包含其他字段):

       <input type="text" id="prenom" name="fname" placeholder="Prenom"><br><br>
       <input type="text" id="nom" name="fname" placeholder="Nom"><br><br>
       <input type="email" id="mail" name="fname" placeholder="Adresse mail"><br><br>
       <input type="file" id="file" name="file" />
   </form>
   <br><button  id="bouton-inscription" >s'inscrire</button>```

然后使用Ajax通过FormData将其上载到:

    var formData = new FormData(); 
    formData.append('file', $('#file')[0].files[0]);

    $.ajax({
        url: './upload',
        cache: false,
        processData: false,
        contentType: false,
        method: 'POST',
        data: formData,
        dataType: 'json'
           })

然后,在服务器端,我想检索文件并使用httpServlet保存它,我使用的代码是我从Oracle文档中“改编”出来的:

@WebServlet(name = "FileUploadServlet", urlPatterns = {"/upload"})
@MultipartConfig
public class FileUploadServlet extends HttpServlet {
    
    protected void processRequest(HttpServletRequest request,HttpServletResponse response)
        throws ServletException, IOException {
        
    response.setContentType("text/html;charset=UTF-8");

    // Create path components to save the file
    final String path = "C:\\Users\\me\\Desktop";
    final Part filePart = request.getPart("file");
    final String fileName = "myFile";

    OutputStream out = null;
    InputStream filecontent = null;
    final PrintWriter writer = response.getWriter();

    try {
        out = new FileOutputStream(new File(path + File.separator
                + fileName));
        filecontent = filePart.getInputStream();

        int read = 0;
        final byte[] bytes = new byte[1024];

        while ((read = filecontent.read(bytes)) != -1) {
            out.write(bytes, 0, read);
        }
        writer.println("New file " + fileName + " created at " + path);
    } catch (FileNotFoundException fne) {
        writer.println("You either did not specify a file to upload or are "
                + "trying to upload a file to a protected or nonexistent "
                + "location.");
        writer.println("<br/> ERROR: " + fne.getMessage());
    } finally {
        if (out != null) {
            out.close();
        }
        if (filecontent != null) {
            filecontent.close();
        }
        if (writer != null) {
            writer.close();
        }
    }
}

但是我在Ajax调用中遇到了一个错误(我用对另一个servlet的另一个Ajax调用处理其他字段,因为它们是文本字段,所以工作得很好)。

我觉得问题一定出在服务器端,因为我在客户端使用的代码随处可见。

如有任何提示,将不胜感激!

谢啦!

编辑:实际上,使用这段代码,文件被正确保存,但仍然存在Ajax错误


共1个答案

匿名用户

问题是双ajax调用,每个调用都有。done,通过不期望从文件上传ajax调用中得到应答,而期望从提交的其余信息中得到一个应答(将用户重定向到另一个页面)来解决这个问题。