springMVC REST 上传文件

参考:

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>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值