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 是第二段代码,复制文件 ,
...全文
相关推荐
springboot-upload-excel:springboot上传excel文件,并将文件中数据保存至mysql数据库
springboot-upload-excel springboot上传excel文件,并将文件中数据保存至mysql数据库
基于springboot实现的文件下载上传
利用springboot实现用户注册登录,完善个人资料,文件上传和文件下载,查看自己上传的文件,还有后台管理功能。数据库文件在压缩包中。
springboot文件上传路径保存数据库并且可以复制路径网页访问图片
里面是完整的案例 自己项目里面摘出来的 项目亲测有效
使用Springboot上传图片并将URL保存到数据库中
使用Spring Boot上传文件的简单Demo
springboot实现文件上传
springboot实现文件上传,file-uploadf


Eclipse
