Hi,大家好,我是编程小6,很荣幸遇见你,我把这些年在开发过程中遇到的问题或想法写出来,今天说一说springboot实现简单的上传下载「终于解决」,希望能够帮助你!!!。
eneity:/** * 主键 */ @Id @Column(length = 50) private String id= UUIDHelper.NewID(); /** * 上传人 */ private String siteId; /** * 文件路径 */ private String path;
controller:
/**
* 文件上传
* @param siteId
* @return RestResponse<实体>
*/
@ApiOperation(value = "文件上传", notes = "文件上传")
@PostMapping("/uploadFile")
public RestResponse<实体> upload(String siteId,
MultipartFile file)
{
RestResponse<实体> restResp = new RestResponse<>();
if (StringUtils.isBlank(siteId)){
return restResp.setMsg("siteId不能为空");
}
try {
//公共地址
String fileSpace="F:/demo_upload";
//定义一个保存数据库的相对目录
String uploadPathDB="/"+siteId+"/file";
// 获取文件名
String filename = file.getOriginalFilename();
if(StringUtils.isNotBlank(filename)){
//确定文件的最终上传路径
String finalFacePath=fileSpace+uploadPathDB+"/"+filename;
//设置保存数据库中的目录
uploadPathDB+=("/"+filename);
//判断目录是否存在,不存在就创建
File outFile=new File(finalFacePath);
if(outFile.getParentFile()!=null||!outFile.getParentFile().isDirectory()){
outFile.getParentFile().mkdirs();
}
//上传
file.transferTo(outFile);
//将上传的文件名保存数据库
DtoFileUpload files = new DtoFileUpload();
files.setSiteId(siteId);
files.setPath(uploadPathDB);
service.save(files);
restResp.setRestStatus(StringUtil.isNull(outFile) ? ERestStatus.UNMATCH_RECORD : ERestStatus.SUCCESS);
return restResp;
}
} catch (IOException e) {
e.printStackTrace();
}
return restResp.setMsg("上传失败");
}
/**
* 文件下载
*/
@ApiOperation(value = "文件下载", notes = "文件下载")
@GetMapping("/download")
public void download(String id, HttpServletResponse resp) throws IOException {
DtoFileUpload file = service.findById(id);
// String fileName=file.getSiteId();
String path=file.getPath();
String downPath="F:/demo_upload/"+path;
FileInputStream fileInputStream=new FileInputStream(downPath);
ServletOutputStream outputStream = resp.getOutputStream();
IOUtils.copy(fileInputStream,outputStream);
fileInputStream.close();
}
简单代码如上,可以直接套用,喜欢可以点个赞哦,谢谢
上一篇
已是最后文章
下一篇
已是最新文章