Native servlet s cannot get data using fileupload

Keywords: Apache

fileupload website URL: you can view detailed documentation, as well as sample code FileUpload – Homehttp://commons.apache.org/proper/commons-fileupload/

Project environment: My front end is written in vue, and the back end is written in native servlet s  

upload.parseRequest(req);

This statement was supposed to get a List, but what I got was empty. Many people in Baidu say that they are automatically converted or filtered, but their environment is ssm or springboot, which is obviously not the reason for my native servlet.

Reason: File buffer and maximum upload of a single file are not set or this setting is too small (I started filling in a 10 as if) Ha-ha, the complete code is finally pasted out

DiskFileItemFactory fif = new DiskFileItemFactory();
            //Set file buffer size to 4M
            fif.setSizeThreshold(1024 * 1024 * 4);
            //Enable temporary folder for caching (temporary) when uploaded files exceed buffer size
            fif.setRepository(new File(req.getSession().getServletContext().getRealPath("/") + "tem"));
            ServletFileUpload upload = new ServletFileUpload(fif);
            //Set the maximum value of a single file to upload to 4M
            upload.setSizeMax(1024 * 1024 * 4);

  This is where I can upload files from the jsp page, but when I use the vue project, cross-domain issues arise.

But it's no use configuring filters

@WebFilter("/*")
public class CrossFilter implements Filter {

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, PATCH, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with, Content-Type, Accept, Origin");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        chain.doFilter(req, res);
    }

    public void init(FilterConfig filterConfig) {}

    public void destroy() {}

}

Later, I wrote another filter that only works with servlets that handle uploaded files, except for the path, which is the same as above (/upload is the path to my servlet that handles uploaded files)

@WebFilter("/upload")  

This will allow my project to work properly on uploading files, and I have not delved into why global resolution cross-domain filters do not work.

Cross-domain issues have arisen:

However, a cross-domain problem has arisen in a classmate project that I collaborated with on git, and even ordinary servlet s cannot be accessed.

Later it was discovered that the filter was given a name (name was typed casually, how to write it at that time forgot) under the project. There are two filters in the project. For convenience, there is one I forgot directly by copying and pasting, only changed the path, name did not change

@WebFilter(filterName="sdf",urlPatterns="/upload")
@WebFilter(filterName="sdf",urlPatterns="/*")

  Reason: After testing, global filters have not even been initialized, so changing their names or not setting them directly solves the problem.

Why I can run normally here and there will be problems in their environment, which I don't understand. In short, it is available. The first is the servlet code, which is not perfect enough, such as restricting the type of file uploaded or anything.

package com.controller;

import com.util.UUIDUtil;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

@WebServlet("/upload")
public class Upload extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        if (ServletFileUpload.isMultipartContent(req)) {
            DiskFileItemFactory fif = new DiskFileItemFactory();
            //Set file buffer size to 4M
            fif.setSizeThreshold(1024 * 1024 * 4);
            //Enable temporary folder for caching (temporary) when uploaded files exceed buffer size
            fif.setRepository(new File(req.getSession().getServletContext().getRealPath("/") + "tem"));
            ServletFileUpload upload = new ServletFileUpload(fif);
            //Set the maximum value of a single file to upload to 4M
            upload.setSizeMax(1024 * 1024 * 4);
            try {
                List<FileItem> items = upload.parseRequest(req);
                Iterator<FileItem> it = items.iterator();
                while (it.hasNext()) {
                    FileItem item = it.next();
                    //1. Text Fields
                    if (item.isFormField()) {
                        //TODO:
                        String name = item.getFieldName();
                        String value = item.getString();
                    }
                    //2. File Domain
                    else {
                        // Determine if the uploaded file is a picture; Non-blank means picture
                        if (ImageIO.read(item.getInputStream()) != null) {
                            String fileName = item.getName();
                            if (fileName == null){
                                throw new Exception();
                            }
                            System.out.println(fileName);
                            String[] split = fileName.split("\\.");
                            System.out.println(split[1]);
                            String lastName = split[1];
                                    // Set file upload path (get real physical path)
                            File file = new File(req.getSession().getServletContext().getRealPath("/") + "img",
                                    UUIDUtil.getUUID()+"."+lastName);
                            item.write(file);
                        } else {
                            System.out.println("Not a picture!");
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}

This is the two dependencies of the derivative, maven derivative

<!--Picture Upload-->
    <!--https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.3.2</version>
    </dependency>
    <!--https://mvnrepository.com/artifact/commons-io/commons-io -->
    <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>2.4</version>
    </dependency>

Posted by trillion on Thu, 04 Nov 2021 09:19:26 -0700