JavaでファイルをMultipartFileに変換する方法


方法1: Commons FileUploadを使用する方法

import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
public MultipartFile convertToMultipartFile(HttpServletRequest request, String parameterName) throws Exception {
    if (ServletFileUpload.isMultipartContent(request)) {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload fileUpload = new ServletFileUpload(factory);
        List<FileItem> items = fileUpload.parseRequest(request);
        for (FileItem item : items) {
            if (item.getFieldName().equals(parameterName)) {
                File tempFile = ((DiskFileItem) item).getStoreLocation();
                MultipartFile multipartFile = new CommonsMultipartFile(tempFile);
                return multipartFile;
            }
        }
    }
    return null;
}

方法2: SpringのMultipartResolverを使用する方法

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest;
import org.springframework.web.multipart.support.StandardServletMultipartResolver;
import javax.servlet.http.HttpServletRequest;
public MultipartFile convertToMultipartFile(HttpServletRequest request, String parameterName) throws Exception {
    if (request instanceof StandardMultipartHttpServletRequest) {
        StandardMultipartHttpServletRequest multipartRequest = (StandardMultipartHttpServletRequest) request;
        MultipartFile multipartFile = multipartRequest.getFile(parameterName);
        return multipartFile;
    } else if (StandardServletMultipartResolver.isMultipart(request)) {
        StandardServletMultipartResolver multipartResolver = new StandardServletMultipartResolver();
        MultipartHttpServletRequest multipartRequest = multipartResolver.resolveMultipart(request);
        MultipartFile multipartFile = multipartRequest.getFile(parameterName);
        return multipartFile;
    }
    return null;
}

以上の方法を使用すると、JavaでファイルをMultipartFileに変換することができます。ご参考までにお使いください。