public String upload(I attachInfo, @RequestParam("file") CommonsMultipartFile file) throws IOException {
AttachService attachService = getAttachService();
Response<StandardAttach> response = Response.newInstance(new StandardAttach());
// 1. 构造附件元数据
StandardAttach attachment = new StandardAttach();
attachment.setBatchId(attachInfo.getBatchId());
attachment.setAttachId(FileType.getValue(attachInfo.getType()));
attachment.setFileName(file.getOriginalFilename());
attachment.setFileSize(file.getSize());
// 2. 校验文件
String validationResult = getAttachService().validate(attachment);
if (!StringUtils.isEmpty(validationResult)) {
response.setFlag(-1);
response.setMsg(validationResult);
return JSON.toJSONString(response);
}
// 3. 保存附件
DiskFileItem diskFileItem = (DiskFileItem) file.getFileItem();
File attachFile = diskFileItem.getStoreLocation();
if (attachment.getFileSize() != 0) {
attachService.saveAttach(attachInfo.getBatchId(), attachment, attachFile);
} else {
attachService.saveAttach(attachInfo.getBatchId(), attachment, null);
}
response.setData(attachment);
return JSON.toJSONString(response);
}
代码一为ARK平台上传接口;
//文件上传
public String uploadFile(MultipartFile file
,String uploadFilePath
){
//获得上传文件的原名
String fileName = file.getOriginalFilename();
String[] sArray = fileName.split("\\.");
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
//创建文件名称
String uploadFileName = sArray[0] + "_" + sdf.format(date) + "." + sArray[1];
String filePath = uploadFilePath+"/"+uploadFileName;
File dest = new File(filePath);
try {
//传输文件
file.transferTo(dest);
} catch (IOException e) {
e.printStackTrace();
}
return uploadFileName;
}
上图所示代码2为公共可实施上传代码块;
/**
* 下载附件
* @param batchId
* @param attachId
* @param response
* @throws UnsupportedEncodingException
*/
public void downloadAttach(String batchId, String attachId, HttpServletResponse response) throws UnsupportedEncodingException {
StandardAttach attachment = localAttachService.getAttachInfo(batchId, attachId);
// 附件不存在处理
if (attachment == null) {
log.error("附件不存在,batchId={},attachId={}", batchId, attachId);
throw new SystemRuntimeException("下载文档时发生异常,请联系系统管理员");
}
String fileName = new String(attachment.getFileName().getBytes("gbk"), "ISO-8859-1");
response.setContentType("application/octet-stream;charset=utf-8");
response.addHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
byte[] b = new byte[1024 * 1024];
int i;
try (InputStream is = localAttachService.getAttach(batchId, attachId);
ServletOutputStream out = response.getOutputStream()) {
while ((i = is.read(b)) > 0) {
out.write(b, 0, i);
}
out.flush();
} catch (IOException e) {
log.error(e.getMessage(), e);
throw new SystemRuntimeException("下载文档时发生异常,请联系系统管理员!");
}
}
如图所示代码三为下载代码;