您的位置:首页 > 编程语言 > Java开发

SpringBoot中的文件上传和下载

2018-09-19 09:24 176 查看
版权声明:如有錯誤,請各位大神及時指出。 https://blog.csdn.net/chen644168023/article/details/82767252

**

SpringBoot中的文件上传和下载

**

SpringBoot中的文件上传和下载

=====Controller下载存入数据库并放入FastDFS

@RequestMapping("/download")
public void download(HttpServletResponse response,String id) throws IOException {
//进入数据库查询单个实体类
Carousel queryone = carouselService.queryone(id);
//在fastfdfs中获取数据对象
//queryone.getGroups()组信息(格式为group1)
//queryone.getImgname()fastfdfs中照片的名称(格式为M00/00/00/wKhqgVugw_GAYHamAAD3zaNpXcw574.JPG)
byte[] bytes = storageClient.downloadFile(queryone.getGroups(), queryone.getImgname(), new DownloadByteArray());
//对浏览器的响应 并设置下载方式指定格式  --inline是浏览器打开  content是用户指定下载
//默认为浏览器打开 需要写入这段代码进行设置 Content`-disposition
response.setContentType("application/x-msdownload;");
response.setHeader("`Content`-disposition", "attachment; filename=" + new String(queryone.getImgurl().getBytes("utf-8"), "ISO8859-1"));
//通过response获取输出流
ServletOutputStream outputStream = response.getOutputStream();
//通过输出流把照片的二进制格式打到前台
outputStream.write(bytes);
//最后关流
outputStream.close();
}

**

----文件上传代码------

写的有点小麻烦,不过也和我的数据库交互了,因为我的项目需求有个回显

@RequestMapping("/upload")
@ResponseBody
public Result addCarousel(MultipartFile aa, HttpServletRequest request,Carousel carousel) throws IOException {
//创建了一个返回值对象
/*这是对象的属性
*@Data
*@ToString
*public class Result implements Serializable {
*private Boolean status;
*private String message
*/;

}

*
Result result = new Result();
//获取我服务器储存文件的文件夹
String realPath = request.getSession().getServletContext().getRealPath("/carouselimg");
carousel.setImgurl(aa.getOriginalFilename());
//这一块我把上传的照片路径写死了,还有待改进
File file = new File("C:\\Users\\chenda\\Desktop\\图片\\"+aa.getOriginalFilename());
//通过fastfds 上传
HashSet mataDataHashMap = new HashSet<MataData>();
StorePath jpg = storageClient.uploadFile(new FileInputStream(file), file.length(), "JPG", mataDataHashMap);
//这是我要添加数据库的信息
carousel.setImgname(jpg.getPath());
carousel.setGroups(jpg.getGroup());
carouselService.addcarousel(carousel);
result.setStatus(true);
result.setMessage("上传成功");
//最后返回就好了
return result;
}


链接: link.

阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: