Java 文件下载

所用技术

SpringBoot、js、Ajax

注:下载不同类型的文件只需要修改,前后端返回和接收的类型,如 application/pdf;text/plain;application/vnd.ms-excel 等

效果图

在这里插入图片描述

前端代码

<div id="fileDiv" class="tab-pane fade">
    <input type="file" id="file" /><br />
    <input type="submit" value="提交" onclick="upload()">
</div>

//直接下载生成的文件
function download() {
    $.ajax({
            url: '/web/download',
            method: 'get',
            processData: false,
            contentType: false,
            responseType: "blob",
            success: function (res, status, xhr) {
                //第一种方式
                let url = window.URL.createObjectURL(new Blob([res], { type: 'text/plain;charset=utf-8' }))
                let link = document.createElement("a")
                link.href = url
                let filename = xhr.getResponseHeader("Content-Disposition").split('attachment; filename=')[1]
                link.setAttribute("download", filename)
                document.body.appendChild(link)
                link.click()
                document.body.removeChild(link)
	
                //第二种方式
                // const data = new Blob([res], { type: 'text/plain;charset=utf-8' })
                // let e = document.createElement("a")
                // let href = window.URL.createObjectURL(data);
                // let filename = xhr.getResponseHeader("Content-Disposition").split('attachment; filename=')[1]
                // e.href = href
                // e.download = decodeURIComponent(filename) //解码
                // document.body.appendChild(e)
                // e.click()
                // document.body.removeChild(e)
                // window.URL.revokeObjectURL(href)
            },
            error: function (err) {
				console.log(err)
            }
        })
}

//先传文件上去解析,再返回新生成的文件
function upload() {
    let f = document.getElementById("file").files[0]
    let data = new FormData()
    data.append("file", f)
    $.ajax({
            url: '/web/upload',
            method: 'post',
            data: data,
            processData: false,
            contentType: false,
            responseType: "blob",
            success: function (res, status, xhr) {
                //第一种方式
                let url = window.URL.createObjectURL(new Blob([res], { type: 'text/plain;charset=utf-8' }))
                let link = document.createElement("a")
                link.href = url
                let filename = xhr.getResponseHeader("Content-Disposition").split('attachment; filename=')[1]
                link.setAttribute("download", filename)
                document.body.appendChild(link)
                link.click()
                document.body.removeChild(link)
	
                //第二种方式
                // const data = new Blob([res], { type: 'text/plain;charset=utf-8' })
                // let e = document.createElement("a")
                // let href = window.URL.createObjectURL(data);
                // let filename = xhr.getResponseHeader("Content-Disposition").split('attachment; filename=')[1]
                // e.href = href
                // e.download = decodeURIComponent(filename) //解码
                // document.body.appendChild(e)
                // e.click()
                // document.body.removeChild(e)
                // window.URL.revokeObjectURL(href)
            },
            error: function (err) {
				console.log(err)
            }
        }) 
}

后端代码

//controller层
@Slf4j
@RestController
@RequestMapping("web")
public class WebController {
    
    @GetMapping("download")
    public void download(HttpServletResponse response) {
        webService.download(response);
    }
    
    @PostMapping("upload")
    public void upload(@RequestParam("file") MultipartFile file, HttpServletResponse response) {
        webService.upload(file, response);
    }
    
}

//service层
@Slf4j
@Service
@AllArgsConstructor
public class WebServiceImpl {
    
    public void download(HttpServletResponse response) {
        //新生成文件的内容
        String s = "context";
        //生成新文件
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/plain");
        response.addHeader("Content-Disposition", "attachment; filename=" + filename);//通过后缀可以下载不同的文件格式
        ServletOutputStream os = null;
        try {
            os = response.getOutputStream();
            response.setContentLength(s.length());
            os.write(s.getBytes());
            System.out.println("新文件已生成,文件名为:" + filename);
            os.close();
        } catch (Exception e) {
            log.error(e.toString());
        } finally {
            try {
                if (os != null)
                    os.close();
            } catch (Exception e) {
                System.out.println(e.toString());
            }
        }
    }
    
    public void upload(MultipartFile file, HttpServletResponse response) {
        //校验文件大小
        if (file.getSize() > 10485760L) //10MB
            throw new RuntimeException("文件大于10MB");

        String filename = file.getOriginalFilename();

        //校验文件
        checkFilename(filename);

        //生成新文件
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/plain");
        response.addHeader("Content-Disposition", "attachment; filename=" + filename);//通过后缀可以下载不同的文件格式
        ServletOutputStream os = null;
        try {
            os = response.getOutputStream();
            byte[] bytes = file.getBytes();
            response.setContentLength(bytes.length);
            os.write(bytes);
            System.out.println("新文件已生成,文件名为:" + filename);
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (os != null)
                    os.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    
    private void checkFilename(String filename) {
        if (!StringUtils.hasText(filename))
            throw new RuntimeException("文件名有误");
        if (!filename.endsWith(".json"))
            throw new RuntimeException("文件类型有误");
    }
    
}

文件下载方式二

    @GetMapping("/down")
    public void download(@RequestParam("uri") String uri, HttpServletResponse response) throws IOException {
        File file = new File(uri);
        if (!file.isFile()) {
            throw new RuntimeException("文件不存在");
        }

        String filename = file.getName();
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));

        try (FileInputStream fileInputStream = new FileInputStream(file);
             BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
             BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(response.getOutputStream())) {
            FileCopyUtils.copy(bufferedInputStream, bufferedOutputStream);
        } finally {
            // 使用的是try-with-resources
        }
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值