Java:Servlet使用AJAX异步上传文件

阅读更多
没有中文乱码问题。
1. 客户端使用HTML + JavaScript(AJAX)


   
    Upload Demo

   

   
   
   



   
Choose file to upload

   




2. 服务器端使用Servlet:Apache commons-fileupload-1.2.1.jar和commons-io-1.3.2.jar

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

@SuppressWarnings("serial")
public class Uploader extends HttpServlet {
    private ServletContext sc;
    private String uploadDir = "downloads";

    @Override
    public void init(ServletConfig config) {
        sc = config.getServletContext();
    }

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        doPost(request, response);
    }

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        request.setCharacterEncoding("UTF-8"); // 防止中文乱码
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);

        try {
            List items = upload.parseRequest(request);
            Iterator itr = items.iterator();
            while (itr.hasNext()) {
                FileItem item = (FileItem) itr.next();
                if (item.isFormField()) {
                    System.out.println("表单参数名:" + item.getFieldName() + ",表单参数值:" + item.getString("UTF-8"));
                } else {
                    if (item.getName() != null && !item.getName().equals("")) {
                        System.out.println("上传文件的大小:" + item.getSize());
                        System.out.println("文件的类型:" + item.getContentType());
                        System.out.println("上传文件的名称:" + item.getName());// 返回上传文件在客户端的完整路径名称

                        File file = new File(sc.getRealPath("/") + File.separatorChar + uploadDir + File.separatorChar
                                + item.getName());
                        item.write(file);
                    } else {
                        response.getWriter().println("没有选择文件");
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().println("上传文件失败");
        }

        response.getWriter().println("Ok");
    }
}

你可能感兴趣的:(servlet,ajax)