What is the usage of fileupload in Java?

One common method for file uploading in Java is to use the Apache Commons FileUpload library. Below is an example code showing how to use FileUpload to handle file uploads.

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

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 org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

@WebServlet("/fileUpload")
@MultipartConfig
public class FileUploadServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    
    private static final String UPLOAD_DIRECTORY = "uploads";
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 检查是否为文件上传请求
        if (!ServletFileUpload.isMultipartContent(request)) {
            PrintWriter writer = response.getWriter();
            writer.println("请求不是文件上传请求");
            writer.flush();
            return;
        }
        
        // 配置上传参数
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(1024 * 1024); // 设置内存缓冲区大小
        factory.setRepository(new File(System.getProperty("java.io.tmpdir"))); // 设置临时目录
        
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setFileSizeMax(1024 * 1024 * 10); // 设置最大文件大小
        
        // 获取上传文件目录的真实路径
        String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY;
        
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdir(); // 如果目录不存在,则创建
        }
        
        try {
            List<FileItem> formItems = upload.parseRequest(request);
            
            if (formItems != null && formItems.size() > 0) {
                // 迭代处理上传的文件
                for (FileItem item : formItems) {
                    if (!item.isFormField()) { // 忽略非文件字段
                        String fileName = new File(item.getName()).getName();
                        String filePath = uploadPath + File.separator + fileName;
                        File storeFile = new File(filePath);
                        
                        // 保存文件到硬盘
                        item.write(storeFile);
                    }
                }
                
                request.setAttribute("message", "文件上传成功");
            }
        } catch (Exception ex) {
            request.setAttribute("message", "文件上传失败: " + ex.getMessage());
        }
        
        // 转发到结果页面
        getServletContext().getRequestDispatcher("/message.jsp").forward(request, response);
    }
}

In this example, the doPost() method handles the POST request for file uploads. Initially, we verify if the request is for uploading a file. Following that, we set up file upload parameters such as temporary directory and file size limit.

Next, we parse the request using the upload.parseRequest(request) method to obtain a list of file items. We then iterate through the file items, excluding non-file fields, and save the uploaded files to a specified directory on the hard drive.

Finally, we save the result information in the request attribute and then forward the request to the result page.

Please note that this is just a simple example demonstrating the basic usage of file uploads. In actual applications, more error handling and security checks are necessary.

广告
Closing in 10 seconds
bannerAds