Java:Servlet getParameter接收multipart/form-data格式数据

  • Post author:
  • Post category:java




引言

当在HTML或者JavaScript中使用表单提交数据时,默认编码格式为

application/x-www-form-urlencoded

,在HTTP报文中可以找到用&与=隔开的信息(因此,我们也可以在JavaScript中手动的send它们),类似下面:

在这里插入图片描述

这种格式可以直接被getParameter获取,但也只能用于传输文本,对于二进制数据是无能为力的。

文件传输需要用到multipart/form-data(注意在JavaScript不要直接设置它,因为二进制数据必须有边界作为数据的结尾,不设置它,JS会自动帮我们加上),类似下面这样:

在这里插入图片描述

网上给的方案要么很麻烦(其实是我这个非专业Java选手看不懂),要么牛头不对马嘴,经过搜索我找到两种方案来解决。



@MultipartConfig

该答案源自stackoverflow,非常简单高效。

If you are working in servlet 3.0+ environment, you can also use its multipart support to easily finish the multipart-data parsing job. Simply add an @MultipartConfig on the servlet class, then you can receive the text data by calling request.getParameter(), very easy.

直接在对应的Servlet上加上@MultipartConfig即可,该注释会自动解析来自multipart/form-data的数据,使得getParameter能够获取到,此外对于文件我们直接只用用getPart获取,比下面的FileUpload要来的方便的多。



FileUpload

这是Apache给的工具包,具体用法就不赘述了,可以参考下面:

package LearnWeb;

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

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

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/serv25")
public class Servlet25 extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload sf = new ServletFileUpload(factory);
        try {
            if (!ServletFileUpload.isMultipartContent(req)) {
                throw new Exception("no multipartcontent");
            }
            List<FileItem> formData = sf.parseRequest(req);
            for (FileItem fi : formData) {
                if (fi.isFormField()) {
                    System.out.println("field_name:" + fi.getFieldName() + ":" + fi.getString("UTF-8"));
                    switch (fi.getFieldName()) {
                        case "name":
                            System.out.println("receive name");
                            break;
                        default:
                            System.out.println("unknow data");
                    }
                } else {
                    String image_name = fi.getName();
                    System.out.println("image_name:" + image_name);
                    if (image_name != "") {
                        String image_dir_path = req.getServletContext().getRealPath("/images/");
                        File image_dir = new File(image_dir_path);
                        if (!image_dir.exists()) {
                            image_dir.mkdir();
                        }
                        String file_name = UUID.randomUUID().toString();
                        String suffix = image_name.substring(fi.getName().lastIndexOf("."));
                        System.out.println("image_dir_path:" + image_dir_path);
                        System.out.println("file_name:" + file_name);
                        System.out.println("suffix:" + suffix);
                        fi.write(new File(image_dir_path, file_name + suffix));
                    } else {
                        throw new Exception("no file receive");
                    }
                }
            }
            resp.getWriter().write("true");
        } catch (Exception e) {
            e.printStackTrace();
            resp.getWriter().write("false");
        }
    }
}

另外附上下载链接:


FileUpload – Download Apache Commons FileUpload



Commons IO – Download Apache Commons IO



参考


java – How can my Servlet receive parameters from a multipart/form-data form? – Stack Overflow



版权声明:本文为qq_45858169原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。