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

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

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

a.选中上传jquery

b:后台显示web

c:上传的文件夹ajax

 

 

 

 

html代码:app

<!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后台代码:ide

@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"); } }
相关文章
相关标签/搜索