繁体   English   中英

REST端点以Java格式发送文件

[英]REST Endpoint to send File in Java

我正在尝试编写可以接收文件的REST API (java) 我的REST API如下所示:

import com.sun.jersey.core.header.FormDataContentDisposition;
import com.sun.jersey.multipart.FormDataParam;

@POST
@Path("/upload")
@Produces(MediaType.TEXT_PLAIN)
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFile(@FormDataParam("file") InputStream uploadedInputStream,
                           @FormDataParam("file") FormDataContentDisposition fileDetail) {
    System.out.println("File Upload invoked");
    return Response.status(200).entity("File saved to " + UPLOAD_FOLDER).build();
}

尝试将文件发送到此端点的客户端如下所示:

HttpPost httppost = new HttpPost(URL);         
httppost.addHeader(HttpHeaders.CONTENT_TYPE,MediaType.MULTIPART_FORM_DATA);

MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

FileBody fileBody = new FileBody(file);
builder.addPart("file", fileBody);                        
builder.setContentType(ContentType.MULTIPART_FORM_DATA);

HttpEntity entity = builder.build();
httppost.setEntity(entity);
HttpResponse responseFromUpload = httpclient.execute(httppost);

int statusCode = responseFromUpload.getStatusLine().getStatusCode();

但是,使用此设置,我无法访问REST端点。 TomcatServer日志说:

[500] Exception occurred : argument type mismatch

然后,我尝试更改REST API定义,如下所示:

public Response uploadFile(MultipartFormDataInput input) {}

通过此设置,我实际上能够访问REST API,并在REST API端记录以下错误:

java.lang.IllegalArgumentException: argument type mismatch

at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.wso2.msf4j.internal.router.HttpMethodInfo.invoke(HttpMethodInfo.java:132)
at org.wso2.msf4j.internal.MSF4JMessageProcessor.dispatchMethod(MSF4JMessageProcessor.java:130)
at org.wso2.msf4j.internal.MSF4JMessageProcessor.receive(MSF4JMessageProcessor.java:72)
at org.wso2.carbon.transport.http.netty.listener.WorkerPoolDispatchingSourceHandler.lambda$publishToWorkerPool$12(WorkerPoolDispatchingSourceHandler.java:125)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)

我一直在网上尝试不同来源的不同设置,但仍无法正确设置。

我可以帮助理解我的设置中缺少的部分以及如何纠正它们以使其工作吗?

谢谢

我想我已经弄明白了这个问题。 我的REST-API端点实际上是MicroService而不是JAX-RS。

因此,HTTP请求的解组与基于JAX-RS的REST端点的解组不同。 我已经使用msf4j微服务框架来编写我的微服务,他们已经解释了如何在他们的文件服务器示例中处理文件上传。

直接调用微服务端点时,我可以将文件作为二进制流发送,如cURL命令中所示:

curl -v -X POST --data-binary @/testPng.png http://localhost:8080/filename.png

谢谢

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM