Servlet从tomcat 7中的多部分表单获取参数[重复]

Posted

技术标签:

【中文标题】Servlet从tomcat 7中的多部分表单获取参数[重复]【英文标题】:Servlet get parameter from multipart form in tomcat 7 [duplicate] 【发布时间】:2013-03-21 17:17:51 【问题描述】:

制作项目需要文件上传。 所以,我正在使用 enctype="multipart/form-data" 通知。

但我无法解析请求中的参数。 我也试过 getPart 但它返回空白字符串。

Servlet 代码 -->

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

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;

public class upload_wall extends HttpServlet 
    private static final long serialVersionUID = 1L;
    // location to store file uploaded
    private static final String UPLOAD_DIRECTORY = "image_upload";
    // upload settings
    private static final int MEMORY_THRESHOLD = 1024 * 1024 * 3;  // 3MB
    private static final int MAX_FILE_SIZE = 1024 * 1024 * 40; // 40MB
    private static final int MAX_REQUEST_SIZE = 1024 * 1024 * 50; // 50MB

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        // checks if the request actually contains upload file
        if (!ServletFileUpload.isMultipartContent(request)) 
            // if not, we stop here
            PrintWriter writer = response.getWriter();
            writer.println("Error: Form must has enctype=multipart/form-data.");
            writer.flush();
            return;
        

        // configures upload settings
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // sets memory threshold - beyond which files are stored in disk
        factory.setSizeThreshold(MEMORY_THRESHOLD);
        // sets temporary location to store files
        factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

        ServletFileUpload upload = new ServletFileUpload(factory);

        // sets maximum size of upload file
        upload.setFileSizeMax(MAX_FILE_SIZE);

        // sets maximum size of request (include file + form data)
        upload.setSizeMax(MAX_REQUEST_SIZE);

        // constructs the directory path to store upload file
        // this path is relative to application's directory
        String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY;

        // creates the directory if it does not exist
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) 
            uploadDir.mkdir();
        

        try 
            @SuppressWarnings("unchecked")
            List<FileItem> formItems = upload.parseRequest(request);
            String fileName1 = "";
            if (formItems != null && formItems.size() > 0) 
                for (FileItem item : formItems) 
                    // processes only fields that are not form fields
                    if (!item.isFormField()) 
                        String fileName = new File(item.getName()).getName();
                        fileName1 += fileName;
                        String filePath = uploadPath + File.separator + fileName;
                        File storeFile = new File(filePath);
                        // saves the file on disk
                        item.write(storeFile);
                    
                
            
            String p_text = request.getParameter("p_data");
            String gallery_nm = request.getParameter("upload_wall_gallery");
            out.println(p_text);
            out.println(gallery_nm);
            //out.println("Upload has been done successfully!"+fileName1);
         catch (Exception ex) 
            out.println(ex.getMessage());
        

    


我在 net 或 *** 上找不到工作示例。

有什么简单的解决办法吗?

【问题讨论】:

【参考方案1】:

由于它是 multipart/form-data 形式,因此对 request.getParameter() 的调用将始终返回 null。在这种情况下,您要做的是

 if (item.isFormField()) 
     System.out.println("Got a form field: " + item.getFieldName()+ " " +item.getString());
  else 
     // it is a file process, the way you are doing it
 

我希望一切正常。

【讨论】:

如果它对您有用,您可以接受并投票赞成这个答案。它将帮助未来的用户:)。【参考方案2】:

问题出在这里:

String p_text = request.getParameter("p_data");
String gallery_nm = request.getParameter("upload_wall_gallery");

从How to upload files to server using JSP/Servlet? answer,您应该将参数设置为FileItem,其中isFormField() 方法返回true。贴出答案中的相关代码片段:

for (FileItem item : formItems) 
    if (item.isFormField()) 
        // Process regular form field (input type="text|radio|checkbox|etc", select, etc).
        String fieldname = item.getFieldName();
        String fieldvalue = item.getString();
        // ... (do your job here)
     else 
        // Process form file field (input type="file").
        String fieldname = item.getFieldName();
        String filename = FilenameUtils.getName(item.getName());
        InputStream filecontent = item.getInputStream();
        // ... (do your job here)
    

解决方案:在调用if (!item.isFormField()) 时,将您的其他请求参数处理移至else 部分。

for (FileItem item : formItems) 
    // processes only fields that are not form fields
    if (!item.isFormField()) 
        String fileName = new File(item.getName()).getName();
        fileName1+=fileName;
        String filePath = uploadPath + File.separator + fileName;
        File storeFile = new File(filePath);
        // saves the file on disk
        item.write(storeFile);
     else 
        //here...
        String fieldname = item.getFieldName();
        String fieldvalue = item.getString();
        if (fieldname.equals("p_data")) 
            //logic goes here...
         else if (fieldname.equals("upload_wall_gallery")) 
            //next logic goes here...
        
    

【讨论】:

@LovepreetSinghBatth,因为您是新来的,请点击声誉下方的检查,将此帖子标记为答案。

以上是关于Servlet从tomcat 7中的多部分表单获取参数[重复]的主要内容,如果未能解决你的问题,请参考以下文章

从 Eureka 表单的多值部分获取表单值

快速“预览”传入的多部分请求

为啥我不能从 VBA 中的多实例表单中获取当前记录 ID

使用 Undertow 的多部分表单数据示例

ios中的多部分表单上传,它是如何完成的?

从访问 vba 中的多值组合框中获取值