使用FormData进行Ajax请求上传文件

匿名 (未验证) 提交于 2019-12-02 21:53:52

Servlet3.0开始提供了一系列的注解来配置Servlet、Filter、Listener等等。这种方式可以极大的简化在开发中大量的xml的配置。从这个版本开始,web.xml可以不再需要,使用相关的注解同样可以完成相应的配置。

我笔记里也有记文件上传:https://www.cnblogs.com/hhmm99/p/9239782.html

a.选中上传

b:后台显示

c:上传的文件夹

html代码:

<!DOCTYPE html> <html lang="en"> <head>     <meta charset="UTF-8">     <title>Ajax上传</title>     <script src="js/jquery-1.12.4.js"></script> </head> <body>     <h1>文件上传</h1>     <form id="f" enctype="multipart/form-data">         UserName:<input type="text" name="userName"><br/>         File1:<input type="file" name="file"><br/>         File2:<input type="file" name="file"><br/>         <input type="button" id="btn" value="提交">     </form> </body> <script>     $(function () {         $("#btn").on("click",function () {             //使用FormData对象来提交整个表单,它支持文件的上传             var formData=new FormData(document.getElementById("f"));             //额外带来一些数据             formData.append("age",14);             //使用ajax提交             $.ajax("ajaxUpload",{                 type:"post",                 data:formData,                 processData:false,//告诉jquery不要去处理请求的数据格式                 contentType:false,//告诉jquery不要设置请求头的类型                 success:function (data) {                     alert(data);                 }             });         })     }) </script> </html>

java后台代码:

@WebServlet("/ajaxUpload") @MultipartConfig //开启上传功能 /**  * @author hh  */ public class FileUploadServlet extends HttpServlet {     @Override     protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {         req.setCharacterEncoding("utf-8");         //获取用户名         String userName=req.getParameter("userName");         //获取年龄         String age=req.getParameter("age");         System.out.println(userName);         System.out.println(age);         //获取项目部署的绝对路径         String uploadPath=req.getServletContext().getRealPath("/photos");         //构建上传的文件夹         File dir=new File(uploadPath);         if(!dir.exists()){             dir.mkdir();         }         //获取所有上传的Part        Collection<Part> parts= req.getParts();         for (Part part:parts) {             //判断上传的类型是否为空,如果为空则不执行上传             if(part.getContentType()!=null){                 //获取文件名                 String fileName=part.getSubmittedFileName();                 //执行上传                 part.write(uploadPath+File.separator+fileName);             }         }         //响应上传成功         resp.getWriter().println("uplaod success");     } }

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!