我正在尝试将包含图像的byte []上传到我的Spring rest服务(在Spring Boot中运行,顺便说一下)作为MultipartFile,我的客户端运行Spring RestTemplate并且我得到了HttpClientErrorException:400 Bad Request。
我的终点:
@RequestMapping(value="/scale/{percent}", method= RequestMethod.POST)
public ResponseEntity scaleImage(@PathVariable("percent") float percent,
@RequestParam("file") MultipartFile file) {
try {
if (!file.isEmpty()) {
byte [] result = transformService.scaleImage(percent, file.getBytes());
return getResponseEntityFromBytes(result);
} else {
return generateBadRequestError();
}
} catch (Exception e) {
if (e instanceof InvalidOperationParameterException) {
// TODO - populate message with bad parameters
LOGGER.log(Level.FINE, "Invalid Parameters: ");
return generateBadRequestError();
} else {
LOGGER.log(Level.SEVERE, "Exception caught: " + e.getMessage(), e);
return generateServerError(e.getMessage());
}
}
}
My Spring RestTemplate客户端:
public void scaleImage(byte[] image, float percent) throws Exception {
String url = "http://localhost:8080/scale/" + percent;
this.testNumberThreads=10;
this.testNumberThreads=10;
MultiValueMap<String, Object> mvm = new LinkedMultiValueMap<>();
mvm.add("file", image);
TransformedResponse r = doPost(url, mvm);
}
private TransformedResponse doPost(String url, MultiValueMap<String, Object> mvm) {
RestTemplate restTemplate = new RestTemplate();
TransformedResponse xr = null;
try {
xr = restTemplate.postForObject(url, mvm, TransformedResponse.class);
} catch (RestClientException e) {
e.printStackTrace();
}
return xr;
}
...
public class TransformedResponse {
byte[] image;
public byte[] getImage() {
return image;
}
public void setImage(byte[] image) {
this.image = image;
}
}
以下是我在客户端看到的例外情况(尚未点击服务器):
org.springframework.web.client.HttpClientErrorException: 400 Bad Request
at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:91)
at org.springframework.web.client.RestTemplate.handleResponseError(RestTemplate.java:588)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:546)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:502)
at org.springframework.web.client.RestTemplate.postForObject(RestTemplate.java:330)
at com.me.image.xform.LoadTest.doPost(LoadTest.java:110)
at com.me.image.xform.LoadTest.loadTestScalePercent(LoadTest.java:75)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:83)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:232)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:89)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:175)
at org.junit.runner.JUnitCore.run(JUnitCore.java:160)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:74)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:211)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:67)
为什么这个请求发布正确?
答案 0 :(得分:9)
我发现了我的问题。我需要将AbstractResource
(在本例中为ByteArrayResource
)添加到我的MultiValueMap
而不是原始字节数组。这是修复它的代码:
public void scaleImage(byte[] image, float percent) throws Exception {
String url = "http://localhost:8080/scale/" + percent;
final byte[] rawBytes = image.clone();
MultiValueMap<String, Object> mvm = new LinkedMultiValueMap<>();
ByteArrayResource bar = new ByteArrayResource(rawBytes) {
@Override
public String getFilename() {
return "Test-"+rawBytes.length + ".jpg";
}
};
mvm.add("file", bar);
TransformedResponse r = doPost(url, mvm);
}
答案 1 :(得分:3)
首先,在使用Spring时,请确保在servlet上下文中定义了正确的MultiPartFile
解析器:
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="52428800"/>
<property name="maxInMemorySize" value="52428800"/>
</bean>
如果你正在使用maven,这个解析器位于spring-web artifact:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${your.spring.version}</version>
</dependency>
然后,创建表单并确保使用正确的enctype
:
<form method="post" action="upload.form" enctype="multipart/form-data">
<input type="file" name="file"/>
<input type="submit"/>
</form>
最后,在控制器中处理文件上传
@RequestMapping(value="/path", method= RequestMethod.POST)
public StringscaleImage(@RequestParam("file") MultipartFile file) {
//....
}
请记住,只有HTML5才支持异步文件上传,而其他人则需要使用某些解决方法(如flash或iframe)。
如果您仍然面临400
错误,请将此记录器(或类似的,取决于日志记录框架)添加到日志记录服务中:
<appender name="console" class="org.apache.log4j.ConsoleAppender">
<param name="Target" value="System.out"/>
<param name="threshold" value="TRACE"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{HH:mm:ss,SSS} %-5p [%c] %m%n"/>
</layout>
</appender>
<logger name="org.springframework.web.method.HandlerMethod">
<level value="TRACE"/>
</logger>
<root>
<priority value="info"/>
<appender-ref ref="console"/>
</root>
它应该输出请求处理期间抛出的异常
答案 2 :(得分:0)
请尝试以下方法,而不是尝试将MultipartFile
作为请求参数传递:
@RequestMapping(value="/scale/{percent}", method= RequestMethod.POST)
public ResponseEntity scaleImage(@PathVariable("percent") float percent,
MultipartHttpServletRequest request) {
Iterator<String> fileNames = request.getFileNames();
MultipartFile uploadedFile = request.getFile(fileNames.next());
String fileName = uploadedFile.getName();
这是我实际上可以接受我的多部分文件的唯一方法。
如果您仍然从此过程中获取空文件,则必须与POST数据的方式有关。