上传下载文件

文件上传

form表单有以下要求:

method = "post" # form表单采用post方式提交数据
enctype = "multipart/form-data" # 使用multipart/form-data方式对表单数据进行编码
type = "file" # 使用input的file控件

后台接收:

@Value("${file.basePath}")
private String basePath;
/**
 * 上传文件
 * @param file 参数名要和前端对应
 * @return
 */
@PostMapping("/upload")
public Result upload(MultipartFile file){
    String originalFilename = file.getOriginalFilename();// 原始文件名
    // 截取文件名后缀
    String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
    // 生成随机文件名(预防重复名字导致文件覆盖)
    String fileName = UUID.randomUUID().toString() + suffix;
    File dir = new File(basePath);
    if(!dir.exists()){
        dir.mkdirs();
    }
    try{
    // file 是一个临时文件, 需要转存到指定位置, 否则本次请求完成后临时文件即刻被删除
        file.transferTo(new File(basePath + fileName));
    }catch(IOException e){
        e.printStackTrace();
    }
    return new Result(1,fileName,"上传成功");
}

文件下载

1.以附件形式下载,弹出保存对话框
2.直接在浏览器中显示

@GetMapping("/download")
public void download(String name, HttpServletResponse response){
    try {
        // 读取要被下载的内容
        File f = new File(basePath + name);
        if(!f.exists()){
            response.getWriter().print(JSON.toJSONString(new Result(0,"找不到文件")));
            return;
        }
        FileInputStream fileInputStream = new FileInputStream(basePath + name);
        // 通过输出流将文件写回浏览器
        ServletOutputStream outputStream = response.getOutputStream();
        response.setContentType("image/jpeg");
        int len = 0;
        byte[] bytes = new byte[1024];
        while((len = fileInputStream.read(bytes)) != -1){
            outputStream.write(bytes,0,len);
            outputStream.flush();
        }
        // 关闭资源
        outputStream.close();
        fileInputStream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
<!--src只需要写上路径,可以直接展示-->
<body>
    <img src="/common/download?name=9ae5af3c-e1bb-4ff7-8850-ba904b502a73.png" alt="">
</body>

form表单的enctype属性

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值