Java 文件下载

所用技术

SpringBoot、js、Ajax

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

效果图

Java 文件下载_第1张图片

前端代码

<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
        }
    }

你可能感兴趣的:(java,java,spring,boot,ajax,js)