参考:
1.http://www.journaldev.com/2573/spring-mvc-file-upload-example-single-multiple-files
上传接口controll:
@RestController
public class OcrController {
private static final Logger logger = LoggerFactory.getLogger(OcrController.class);
@Resource
private OcrService ocrService;
@RequestMapping(value="/api/ocr",method = RequestMethod.POST)
public Response getOcrResponse(@RequestParam(value = "file", required = false) MultipartFile file ) {
logger.info("get OCR services start...");
OcrFailResponse ocrFailResponse = null;
Response ocrResponse = null;
File serverFile = createFileOnServer(file);
if(serverFile.exists()){
ocrResponse = ocrService.getOcrService(serverFile);
return ocrResponse;
}else{
ocrFailResponse = new OcrFailResponse();
ocrFailResponse.setCode(Response.RESULT_CODE_ERROR);
ocrFailResponse.setMessage(OcrFailResponse.RESULT_MESSAGE_FILEUPLOAD_ERROR);
return ocrFailResponse;
}
}
public File createFileOnServer(MultipartFile file){
File serverFile = null;
if (!file.isEmpty()) {
try {
byte[] bytes = file.getBytes();
// Creating the directory to store file
String filename = "OcrUplaod_" + TimeUtil.genDate() + ".png";
File dir = new File(SystemConfig.getFile_store_path());
if (!dir.exists())
dir.mkdirs();
// Create the file on server
serverFile = new File(dir.getAbsolutePath()
+ File.separator + filename);
BufferedOutputStream stream = new BufferedOutputStream(
new FileOutputStream(serverFile));
stream.write(bytes);
stream.close();
logger.info("Server File Location="
+ serverFile.getAbsolutePath());
} catch (Exception e) {
logger.error("You failed to upload " + file + " => " + e.getMessage());
}
} else {
logger.debug("You failed to upload " + file + " because the file was empty.");
}
return serverFile;
}
}
注意要导入commons-fileupload.jar,要不会报错:
the current request is not a multipart request
compile 'commons-fileupload:commons-fileupload:1.3.2'
添加bean:
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
</bean>
这里可以配置文件上传大小限制:
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8"/>
<property name="maxUploadSize" value="#{20*1024*1024}"/>
<property name="resolveLazily" value="true"/>
</bean>