我正在尝试将多部分文件作为表单数据发布到REST服务,该文件在REST服务端保存后返回一个URL。在邮递员中,请求看起来像这样。
我有一个Spring Boot服务,它具有通过jquery fileuploader获取Multipart文件形式前端的方法。我需要将文件发布到邮递员发送并保存在那里的上述URL中。我想我必须在Spring引导服务中构造表单数据。下面是一些Spring Boot服务的快照。
控制器端。
@RequestMapping(method = RequestMethod.POST, value = "/file-upload/{profileName:.+}")
public Attachment uploadFile(@RequestParam("file") MultipartFile input,
@PathVariable("profileName") String profileName) throws IOException {
Attachment attachment = new Attachment();
if (input != null) {
log.info("Upload a new attachment item" + input.getName());
byte[] fileByteArray = input.getBytes();
attachment.setEncodedFile(Utils.encodeBytes(fileByteArray));
attachment.setFileName(input.getOriginalFilename());
socialMediaService.uploadMedia(input, profileName);
}
return attachment;
}
SocialMediaService
public String uploadMedia(MultipartFile input, String profileName) {
String mediaUploadPath = "wall_attach/lenne-public";
Map < String, String > params = new HashMap < > ();
String mediaUploadFullPath =
UrlBuilder.build(System.getenv(Constants.HUBZILLA_URL), mediaUploadPath, params);
if (!isRestServiceProvided) {
restService = new RestService(RequestType.POST, mediaUploadFullPath);
}
MultipartEntityBuilder builder = restService.getEntityBuilder();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
try {
builder.addBinaryBody("userfile", input.getBytes(), ContentType.DEFAULT_BINARY, input.getOriginalFilename());
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
String strResp = restService.execute(profileName, Constants.HUBZILLA_PW);
return strResp;
}
return null;
}
RestService类
public class RestService {
private Logger log;
private HttpClient client = null;
private HttpRequest request = null;
private RequestType reqType = null;
private String body;
MultipartEntityBuilder builder = null;
public RestService() {
this.log = LoggerFactory.getLogger(RestService.class);
}
/**
* Create REST service with external parameters.
*
* @param reqType RequestType
* @param client HttpClient
* @param request External HttpRequest
*/
public RestService(RequestType reqType, HttpClient client, HttpRequest request, Logger log) {
this.reqType = reqType;
this.client = client;
this.request = request;
this.log = log;
}
/**
* Create REST service string parameters.
*
* @param reqType RequestType
* @param fullPath Full path of REST service
*/
public RestService(RequestType reqType, String fullPath) {
this.client = HttpClientBuilder.create().build();
this.reqType = reqType;
this.log = LoggerFactory.getLogger(RestService.class);
if (reqType == RequestType.GET) {
this.request = new HttpGet(fullPath);
} else if (reqType == RequestType.POST) {
this.request = new HttpPost(fullPath);
} else if (reqType == RequestType.DELETE) {
this.request = new HttpDelete(fullPath);
}
}
/**
* Execute REST service without authentication.
*
* @return - Result of the service.
*/
public String execute() {
return execute(null, null);
}
/**
* Execute REST web service with basic authentication.
*
* @return - Result of the service.
*/
public String execute(String user, String password) {
try {
if (user != null && password != null) {
StringBuilder authString = new StringBuilder();
authString.append(user).append(":").append(password);
String authBase = new String(
Base64.getEncoder().encode(authString.toString().getBytes(Charset.forName("UTF-8"))));
String authType = "Basic ";
String authHeader = authType + authBase;
request.setHeader(HttpHeaders.AUTHORIZATION, authHeader);
}
HttpResponse response = null;
if (this.reqType == RequestType.GET) {
HttpGet get = (HttpGet) request;
response = client.execute(get);
} else if (this.reqType == RequestType.POST) {
HttpPost post = (HttpPost) request;
if (body != null) {
StringEntity stringEntity = new StringEntity(body);
post.setEntity(stringEntity);
}
if (builder != null) {
HttpEntity entity = builder.build();
post.setEntity(entity);
}
response = client.execute(post);
} else {
throw new NotImplementedException();
}
if (response != null && (response.getStatusLine().getStatusCode() == Status.OK.getStatusCode()
|| response.getStatusLine().getStatusCode() == Status.CREATED.getStatusCode())) {
HttpEntity entity = response.getEntity();
return EntityUtils.toString(entity);
}
} catch (Exception e) {
log.error("External service call failed ", e);
}
return null;
}
public void setBody(String body) {
this.body = body;
}
public MultipartEntityBuilder getEntityBuilder() {
this.builder = MultipartEntityBuilder.create();
return this.builder;
}
}
执行剩余服务上载媒体方法后,我的问题没有得到任何结果。但是通过邮递员可以很好地工作。
有人可以让我知道我在想什么吗?我在Java中构造表单数据的方式正确吗?
谢谢。
答案 0 :(得分:0)
尝试在@RequestMapping中添加消耗参数,如下所示(consumes =“ multipart / form-data”)
@RequestMapping(method = RequestMethod.POST, consumes = "multipart/form-data" ,value = "/file-upload/{profileName:.+}")
public Attachment uploadFile(@RequestParam("file") MultipartFile input,
@PathVariable("profileName") String profileName) throws IOException {
----
----
}
这里还有另一个相关问题: Trying to upload MultipartFile with postman 请阅读此链接中答案下方的评论。 希望对您有帮助!