收到 415 不支持的媒体类型,针对多部分文件请求。

huangapple go评论77阅读模式
英文:

Receiving 415 Unsupported Media Type for a multipartfile request

问题

我想使用javax和Spring框架(不是Spring Boot)编写一个API,该API应该接受POST请求并将文件上传到运行控制器的Tomcat服务器。问题是,我已经有了所有必要的代码,但是当我调用API时,我会收到415不支持的类型错误。所需的代码定义如下:

@POST
@Path("file/{productName}")
public String uploadFile(@RequestParam("file") MultipartFile file, @PathParam("productName") String productName) throws IOException {
    File folderPath = new File("/Users/homeDirectory/Desktop/FileUploadTest");
    FileOutputStream fout = new FileOutputStream(folderPath + "/" + file.getOriginalFilename());
    fout.write(file.getBytes());
    fout.close();
    return "Response";
}

我还有另一个客户端(子模块),它正在使用Unirest调用上传端点。文件类型可以是CSV或PNG:

File f = new File("/Users/homeDirectory/Desktop/aggregateReport.csv");
HttpResponse<String> response = Unirest.post("http://localhost:8080/report-rest/report/v1/file/test123")
        .field("file", f).asString();

在服务器端,我看到以下错误:

Apr 04, 2020 10:13:33 PM org.apache.cxf.jaxrs.utils.JAXRSUtils logMessageHandlerProblem
SEVERE: No message body reader has been found for class org.springframework.web.multipart.MultipartFile, ContentType: multipart/form-data;boundary=1MbhkGkO-__me1XVpPXpsLEWcSMn4ltIz4
Apr 04, 2020 10:13:33 PM org.apache.cxf.jaxrs.impl.WebApplicationExceptionMapper toResponse
WARNING: javax.ws.rs.WebApplicationException: HTTP 415 Unsupported Media Type
    ...

(注意:上面的文本是您提供的内容的翻译,不包含任何额外的信息。)

英文:

I want to write an API using javax and spring framework(not spring boot) which is supposed to take a post request and upload file to the server where the controller is running in tomcat server. The problem is I've all required code but when I call the API I get 415 unsupported type error. Required code defined as follows:

@POST
@Path(&quot;file/{productName}&quot;)
public String uploadFile(@RequestParam(&quot;file&quot;) MultipartFile file, @PathParam(&quot;productName&quot;) String productName) throws IOException {
	File folderPath = new File(&quot;/Users/homeDirectory/Desktop/FileUploadTest&quot;);
	FileOutputStream fout = new FileOutputStream(folderPath+&quot;/&quot;+ file.getOriginalFilename());
	fout.write(file.getBytes());
	fout.close();
	return &quot;Response&quot;;

I've another client(submodule) who is calling the upload endpoint using Unirest. File Type can be CSV or PNG

File f = new File(&quot;/Users/homeDirectory/Desktop/aggregateReport.csv&quot;);
	HttpResponse&lt;String&gt; response = Unirest.post(&quot;http://localhost:8080/report-rest/report/v1/file/test123&quot;)
			.field(&quot;file&quot;, f).asString();

and at server side I see the following error:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-html -->

Apr 04, 2020 10:13:33 PM org.apache.cxf.jaxrs.utils.JAXRSUtils logMessageHandlerProblem
SEVERE: No message body reader has been found for class org.springframework.web.multipart.MultipartFile, ContentType: multipart/form-data;boundary=1MbhkGkO-__me1XVpPXpsLEWcSMn4ltIz4
Apr 04, 2020 10:13:33 PM org.apache.cxf.jaxrs.impl.WebApplicationExceptionMapper toResponse
WARNING: javax.ws.rs.WebApplicationException: HTTP 415 Unsupported Media Type
	at org.apache.cxf.jaxrs.utils.JAXRSUtils.readFromMessageBody(JAXRSUtils.java:1339)
	at org.apache.cxf.jaxrs.utils.JAXRSUtils.processParameter(JAXRSUtils.java:824)
	at org.apache.cxf.jaxrs.utils.JAXRSUtils.processParameters(JAXRSUtils.java:788)
	at org.apache.cxf.jaxrs.interceptor.JAXRSInInterceptor.processRequest(JAXRSInInterceptor.java:212)
	at org.apache.cxf.jaxrs.interceptor.JAXRSInInterceptor.handleMessage(JAXRSInInterceptor.java:77)
	at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:308)
	at org.apache.cxf.transport.ChainInitiationObserver.onMessage(ChainInitiationObserver.java:121)
	at org.apache.cxf.transport.http.AbstractHTTPDestination.invoke(AbstractHTTPDestination.java:254)
	at org.apache.cxf.transport.servlet.ServletController.invokeDestination(ServletController.java:234)
	at org.apache.cxf.transport.servlet.ServletController.invoke(ServletController.java:208)
	at org.apache.cxf.transport.servlet.ServletController.invoke(ServletController.java:160)
	at org.apache.cxf.transport.servlet.CXFNonSpringServlet.invoke(CXFNonSpringServlet.java:180)
	at org.apache.cxf.transport.servlet.AbstractHTTPServlet.handleRequest(AbstractHTTPServlet.java:299)
	at org.apache.cxf.transport.servlet.AbstractHTTPServlet.doPost(AbstractHTTPServlet.java:218)
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:661)
	at org.apache.cxf.transport.servlet.AbstractHTTPServlet.service(AbstractHTTPServlet.java:274)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
	at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
	at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:496)
	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
	at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
	at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:650)
	at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
	at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803)
	at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
	at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:790)
	at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1468)
	at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
	at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
	at java.lang.Thread.run(Thread.java:748)

<!-- end snippet -->

答案1

得分: 3

@Paul 谢谢你提供正确的方向在这里发布正确的代码以便他人帮助

@POST
@Path("file/{productName}")
public Response uploadFile(MultipartBody multipartBody, @PathParam("productName") String productName) {
    List<Attachment> attachments = multipartBody.getAllAttachments();
    List<DataHandler> dataHandlers = attachments.stream().map(Attachment::getDataHandler).collect(Collectors.toList());
    dataHandlers.forEach(dataHandler -> {
        String fileName = dataHandler.getName();
        try {
            InputStream fileContentStream = dataHandler.getInputStream();
            if (Objects.isNull(fileContentStream)) {
                LOGGER.error("请求中收到了空流");
            } else {
                String directoryPath = fileUtil.createDirectoryToSaveFiles(uploadProperties.getSourceDirectoryLocation(), productName);
                File fileToWrite = fileUtil.createFileToWrite(directoryPath + File.separator + fileName);
                fileUtil.writeContentInFile(fileContentStream, fileToWrite);
            }
        } catch (Exception e) {
            throw new RuntimeException("写入文件时出错:" + e.getMessage());
        }
    });
    return Response.ok("示例字符串").build();
}
英文:

@Paul Thank you providing the right direction. Posting correct code here so other's to help

@POST
@Path(&quot;file/{productName}&quot;)
public Response uploadFile(MultipartBody multipartBody, @PathParam(&quot;productName&quot;) String productName) {
	List&lt;Attachment&gt; attachments = multipartBody.getAllAttachments();
	List&lt;DataHandler&gt; dataHandlers = attachments.stream().map(Attachment::getDataHandler).collect(Collectors.toList());
	dataHandlers.forEach(dataHandler -&gt; {
		String fileName = dataHandler.getName();
		try {
			InputStream fileContentStream = dataHandler.getInputStream();
			if (Objects.isNull(fileContentStream)) {
				LOGGER.error(&quot;Null Stream received in request&quot;);
			} else {
				String directoryPath = fileUtil.createDirectoryToSaveFiles(uploadProperties.getSourceDirectoryLocation(), productName);
				File fileToWrite = fileUtil.createFileToWrite(directoryPath + File.separator + fileName);
				fileUtil.writeContentInFile(fileContentStream, fileToWrite);
			}
		} catch (Exception e) {
			throw new RuntimeException(&quot;Something went wrong while writing to file &quot;+ e.getMessage());
		}
	});
	return Response.ok(&quot;Sample String&quot;).build();
}

huangapple
  • 本文由 发表于 2020年4月5日 11:20:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/61037605.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定