1.上传文件的时候
SPRING REST: The request was rejected because no multipart boundary was found
org.springframework.web.multipart.MultipartException: Could not parse multipart servlet request;
nested exception is org.apache.commons.fileupload.FileUploadException:
the request was rejected because no multipart boundary was found**"
代码如下:
@Controller
public class MultipleFilesRecieve { @RequestMapping ( value = "/saveMultiple", method = RequestMethod.POST )
public String save( FileUploadForm uploadForm ) {
List<MultipartFile> files = uploadForm.getFiles( );
List<String> fileNames = new ArrayList<String>( );
if ( null != files && files.size( ) > 0 ) {
for ( MultipartFile multipartFile : files ) {
String fileName = multipartFile.getOriginalFilename( );
fileNames.add( fileName );
}
}
return "multifileSuccess";
}
}
以上问题,根据Stack Overflow大神所说:
The problem isn't in your code - it's in your request. You're missing boundary in your multipart request. As it said in specification:
问题不在您的代码中 - 而在您的请求中。 您在多部分请求中缺少边界。 正如它在规范中所说:
The Content-Type field for multipart entities requires one parameter, "boundary", which is used to specify the encapsulation boundary. The encapsulation boundary is defined as a line consisting entirely of two hyphen characters ("-", decimal code 45) followed by the boundary parameter value from the Content-Type header field.
解决方法就是,把header中定义的 form-data 请求头删掉(Don't supply Content-Type header in the request. It will work.)
2.在使用Spring的RestTemplate进行文件上传的时候包下面的错误,好难找原因,又是Stack Overflow给了启发,其实这个RestTemplate好像不太好上传,因为我是除了文件还有别的参数
Could not write JSON: No serializer found for class java.io.FileDescriptor and no properties discovered to create BeanSerializer
![](https://img.haomeiwen.com/i13489956/a2fd8c320293c7fa.png)
解决,使用apache的HttpPost
![](https://img.haomeiwen.com/i13489956/499df5b14cdf1449.png)
![](https://img.haomeiwen.com/i13489956/ae0bf5dd48125453.png)
3.使用RestTemplate时候出现的错误
org.springframework.web.client.RestClientException: Could not write request: no suitable HttpMessageConverter found for request type [org.springframework.util.LinkedMultiValueMap] and content type [application/x-www-form-urlencoded;charset=UTF-8]
post方法使用了MultiValueMap来封装参数,但是无法找到合适的类型转换,仔细查看我的RestTemplate对象获取方式是如下的:
public static RestTemplate getInstance(String charset) {
StringHttpMessageConverter m = new StringHttpMessageConverter(Charset.forName(charset));
RestTemplate restTemplate = new RestTemplateBuilder().additionalMessageConverters(m).build();
return restTemplate;
}
我是直接@Autowired注入的RestTemplate对象
使用了RestTemplateBuilder来创建RestTemplate对象,该方式只会为restTemplate模板初始化一个HttpMessageConverter(注:StringHttpMessageConverter间接实现HttpMessageConverter接口)
直接new的话会多几个Converter
![](https://img.haomeiwen.com/i13489956/1a357c15424446e7.png)
网友评论