SpringBoot中的文件上传和下载

**

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.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值