springboot上传文件并保存到数据库
@PostMapping("/UploadFile")
@ResponseBody
public String uploadFile(@RequestParam MultipartFile file,
HttpServletRequest request) {
if (file.isEmpty()) {
return "-1";
}
String uploadTempFloder ="/upload/";
logger.info("upload starting........");
//得到上传的文件名
String originalFilename = file.getOriginalFilename();
logger.info("上传文件名:" + originalFilename);
//后缀名
String suffix = originalFilename.substring(originalFilename.lastIndexOf("."),originalFilename.length());
//保存到资源表中
Asset asset = new Asset();
asset = Asset.insertBean(asset);
//设置值
asset.setAssetName(originalFilename);
asset.setAssetType(file.getContentType());
asset.setFileSize(file.getSize());
assetService.inserAsset(asset);
//得到文件 并且改名
String storePath = uploadTempFloder + DateUtil.getSystemDateStr()+"/" + asset.getId() +suffix;
asset.setStorePath(storePath);
assetService.updateAsset(asset);
//全路径
String fileAllPath = uploadPath + uploadTempFloder + DateUtil.getSystemDateStr()+"/" + asset.getId() +suffix;
File newFile = new File(fileAllPath);
if (!newFile.getParentFile().exists()){
newFile.getParentFile().mkdirs();
}
try {
FileUtil.writeIntoOut(file.getInputStream(),new FileOutputStream(storePath));
} catch (IOException e) {
return "-1";
}
logger.info("upload finish........");
return CastUtil.castString(asset.getId());
}
public static void writeIntoOut(InputStream ins, OutputStream out) {
try {
if (ins != null && out != null) {
byte[] arr = new byte[10 * 1024];
int len = ins.read(arr);
while (len > 0) {
out.write(arr, 0, len);
len = ins.read(arr);
}
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (ins != null) {
try {
ins.close();
} catch (IOException e) {
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
}
}
}
}
上传post请求、、 uploadFile 然后在action中这么处理, Asset 是对应的资源表,FileUtil.writeIntoOut 是第二段代码,复制文件 ,