Home >Web Front-end >JS Tutorial >How FormData implements Ajax request to upload files (code attached)

How FormData implements Ajax request to upload files (code attached)

不言
不言Original
2018-08-15 10:55:171774browse

The content of this article is about how FormData implements Ajax request to upload files (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Servlet3.0 began to provide a series of annotations to configure Servlet, Filter, Listener, etc. This method can greatly simplify the configuration of a large amount of xml during development. Starting from this version, web.xml is no longer needed, and the corresponding configuration can also be completed using relevant annotations.

a. Select upload

b: Display in the background

c: Uploaded folder

html code:

<!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 background code:

@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");
    }
}

Related recommendations:

ajax php file upload code

ajax file upload

PHP jQuery Ajax file upload without refreshing

The above is the detailed content of How FormData implements Ajax request to upload files (code attached). For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn