web-dev-qa-db-ja.com

Tomcat 7のマルチパートフォームからサーブレット取得パラメーター

プロジェクトを作成し、ファイルのアップロードが必要です。そのため、enctype = "multipart/form-data" informを使用しています。

しかし、リクエストからパラメータを解析できません。 getPartも試しましたが、空の文字列を返しました。

サーブレットコード->

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またはstackoverflowで動作する例を見つけることができません。

簡単な解決策はありますか?

14

問題はここにあります:

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

JSP/Servletを使用してファイルをサーバーにアップロードする方法? から、パラメータを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...
        }
    }
}
_
22
Luiggi Mendoza

_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
 }
_

すべてがうまくいくことを願っています。

3
kaysush