首页 > 解决方案 > 尝试使用 JAX-RS 类上传文件时,“Servlet 上不存在多部分配置”

问题描述

我有以下 JAX-RS 类可以从浏览器上传文件(在 Wildfly 14 中实现)。问题是我得到了错误multipart config was not present on Servlet。由于我在课堂上注释了@Consumes({ MediaType.MULTIPART_FORM_DATA })我不确定缺少什么。如何解决这个问题?

@Produces({ MediaType.APPLICATION_JSON })
@Consumes({ MediaType.MULTIPART_FORM_DATA })
public class FileUploadService {

    @Context
    private HttpServletRequest request;

    @POST
    @Path("/upload")
    public Response processUpload() throws IOException, ServletException {

        String path = "/mypath";    

        for (Part part : request.getParts()) {

            String fileName = getFileName(part);
            String fullPath = path + File.separator +  fileName;

            // delete file if exists
            java.nio.file.Path path2 = FileSystems.getDefault().getPath(fullPath);
            Files.deleteIfExists(path2);

            // get file input stream
            InputStream fileContent = part.getInputStream();
            byte[] buffer = new byte[fileContent.available()];
            fileContent.read(buffer);
            File targetFile = new File(fullPath);

            // write output file
            OutputStream outStream = new FileOutputStream(targetFile);
            outStream.write(buffer);
            outStream.close();
        }

        return Response.ok("OK").build();
    }


    private String getFileName(Part part) {
        for (String content : part.getHeader("content-disposition").split(";")) {
            if (content.trim().startsWith("filename"))
                return content.substring(content.indexOf("=") + 2, content.length() - 1);
        }
        return "";
    }

}

标签: file-uploadjax-rsresteasy

解决方案


推荐阅读