在 Java 中发送文件的 REST 端点

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(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 端点实际上是一个微服务而不是 JAX-RS。

因此,HTTP 请求的解组与基于 JAX-RS 的 REST 端点发生的解组不同。我用过msf4j microservices framework to write my microservice and they have explained how to handle file upload in their fileserver example

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

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

谢谢