从Servlet上传文件

时间:2017-03-20 12:05:29

标签: java servlets file-upload

我正在尝试获取用户在servlet中上传的文件。我是从here读到的。但是upload.parseRequest(request)给出了编译时错误,说RequestContext不能应用于HttpServletRequest对象。为什么不在这里工作?我还在WEB-INF / lib文件夹中包含了commons-fileupload-1.3.2和commons-io-2.5。

DiskFileItemFactory factory = new DiskFileItemFactory();
    // maximum size that will be stored in memory
    factory.setSizeThreshold(maxMemSize);
    // Location to save data that is larger than maxMemSize.
    factory.setRepository(new File("c:\\temp"));

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    // maximum file size to be uploaded.
    upload.setSizeMax( maxFileSize );

    try{
        // Parse the request to get file items.
        List fileItems = upload.parseRequest(request);}
    catch(Exception e){
    }

1 个答案:

答案 0 :(得分:0)

在servlet 3.0中你可以使用:

示例类上传文件:

package com.app.upload;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.http.Part;

/**
 * 
 * @author user-sqli date: 12/05/2016 17:30
 */
public class UploadPicture {
    private static final String EXTENSION = ".";
    public static final String SAVE_DIR = "uploadImage";
    private static UploadPicture uploadPicture = null;
    private static final Logger LOGGER = Logger.getLogger(UploadPicture.class
            .getName());

    private UploadPicture() {
    }

    public String TranseferPicture(Part part, String appPath) {
        String savePath = appPath + File.separator + SAVE_DIR;
        File fileSaveDir = new File(savePath);
        if (!fileSaveDir.exists()) {
            fileSaveDir.mkdir();
        }

        String fileName = new SimpleDateFormat("yyyyMMdd_HHmmss")
                .format(new Date());
        String nameImage = fileName + EXTENSION + getExtensionImage(part);
        try {
            part.write(savePath + File.separator + nameImage);
            LOGGER.log(Level.FINE, "Upload  Picture to {0} ", savePath
                    + File.separator + nameImage);

        } catch (IOException ex) {
            LOGGER.log(Level.SEVERE, ex.toString(), ex);
        }
        return nameImage;
    }

    private String getExtensionImage(Part part) {

        return part.getContentType().split("/")[1];
    }

    public static UploadPicture createNewInstance() {
        if (uploadPicture == null) {
            uploadPicture = new UploadPicture();
        }
        return uploadPicture;
    }
}

并在你的servlet中这样:

import java.io.IOException;

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

import com.app.upload.UploadPicture;

/**
 * 
 * @author user-sqli date: 12/05/2016 17:42
 */
@WebServlet(urlPatterns = "/upload", loadOnStartup = 1)
@MultipartConfig(fileSizeThreshold = 1024 * 1024 * 2, // 2MB
maxFileSize = 1024 * 1024 * 10, // 10MB
maxRequestSize = 1024 * 1024 * 50)
// 50MB
public class ControllerUploadPicture extends HttpServlet {

    private static final long serialVersionUID = 1L;

    @Override
    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        String appPath = request.getServletContext().getRealPath("");

        Part part = request.getPart("file");
        UploadPicture.createNewInstance().TranseferPicture(part, appPath);

        getServletContext().getRequestDispatcher("/show.jsp").forward(request,
                response);
    }

}

在你的jsp文件中

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Upload file</title>
</head>
<body>
    <form method="post" action="upload" enctype="multipart/form-data">
        <input type="file" name="file" /><br /> <input type="submit"
            value="Upload" />
    </form>

</body>
</html>

我的帐户github

中提供了此示例

https://github.com/abdedaime/UploadPictureServlet