微信官网登陆,一键优化ppt,网站查询域名ip查询,小视频制作软件appspringboot文件上传和下载的简单思路 文件上传文件下载 文件上传
在springboot中#xff0c;上传文件只需要在接口中通过 MultipartFile 对象来获取前端传递的数据#xff0c;然后将数据存储#xff0c;并且返回一个对外访问路径即可。一般对于上传文件的文件名#xff0c… springboot文件上传和下载的简单思路 文件上传文件下载 文件上传
在springboot中上传文件只需要在接口中通过 MultipartFile 对象来获取前端传递的数据然后将数据存储并且返回一个对外访问路径即可。一般对于上传文件的文件名都要通过uuid进行处理。
RestController
RequestMapping(/file)
public class FileController {// 服务器存储位置private static String parentPath D:\\IdeaProjects\\demoZ\\src\\main\\resources\\static\\;// 上传接口RequestMapping(/upload)public String uploadFile(RequestParam MultipartFile file) throws IOException {String originalFilename file.getOriginalFilename(); // 获取文件名String type file.getContentType(); // 获取文件类型long size file.getSize(); // 获取文件大小// 这里只对一种类型进行了简单判断可以自行修改if (image/jpeg.equals(type)){type .jpg;}// 构建uuid作为唯一标识String uuid UUID.randomUUID().toString()type;File uploadFile new File(parentPathuuid);// 判断父级目录是否存在不存在则创建File parentFile uploadFile.getParentFile();if(!parentFile.exists()){parentFile.mkdirs();}// 文件存储到磁盘上file.transferTo(uploadFile);// 返回对外访问路径return http://localhost:9090/file/uuid;}
}文件下载
文件下载的话只需要在接口中传入文件的uuid名称然后通过流的方式直接输出即可。
RestController
RequestMapping(/file)
public class FileController {private static String parentPath D:\\IdeaProjects\\demoZ\\src\\main\\resources\\static\\;// 文件上传接口....// 文件下载接口RequestMapping(/{uuid})public void download(PathVariable String uuid, HttpServletResponse response) throws IOException {// 通过response将数据输出// 根据文件的唯一标识码获取文件File uploadFile new File(parentPathuuid);// 设置输出流的格式ServletOutputStream os response.getOutputStream();response.addHeader(Content-Disposition,attachment;filename URLEncoder.encode(uuid,UTF-8));response.setContentType(application/octet-stream);// 创建文件输入流FileInputStream fis new FileInputStream(uploadFile);// 读取文件的字节流byte[] buf new byte[1024];int readLen 0;while ((readLenfis.read(buf))!-1){// 边读边写os.write(buf,0,readLen);}os.flush();os.close();}
}tips:通过文件上传的返回值即可测试下载接口 http://localhost:9090/file/59038923-ea78-40df-970e-70f49dc966b3.jpg 这里的话为了简单就只写了后端的文件上传和下载没有涉及到数据库的文件信息存储正常情况下是根据你文件的唯一标识去获取下载这张图片的url地址的。不过接口写的没问题哈