Java中文件上传/下载

文件上传

https://www.cnblogs.com/kzyuan/p/12482841.html

文件下载

https://www.cnblogs.com/kzyuan/p/12493993.html

方式一

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.ObjectUtil;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * @author JHL
 * @version 1.0
 * @since : JDK 11
 */
public class CommonUtil {

    /**
     * 文件下载工具
     */
    public static void fileDownLoad(HttpServletResponse response, File file) throws IOException {
        if (ObjectUtil.isNull(file)) {
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write("{\"msg\":\"请先登录设备!\",\"code\":500}");
            response.flushBuffer();
        }
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(file.getName(), StandardCharsets.UTF_8));
        byte[] buff = new byte[1024];
        BufferedInputStream bis = null;
        OutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            bis = new BufferedInputStream(new FileInputStream(file));
            int read = bis.read(buff);
            while (read != -1) {
                outputStream.write(buff, 0, buff.length);
                outputStream.flush();
                read = bis.read(buff);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            IoUtil.close(bis);
            IoUtil.close(outputStream);
        }
    }
}

方式二

import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.net.MalformedURLException;

/**
 * @author JHL
 * @version 1.0
 * @since : JDK 11
 */
@RestController
@RequestMapping("/test")
public class TestController {

    @GetMapping
    public ResponseEntity<Resource> downloadFile() throws MalformedURLException {
        // 从资源路径下载
        // Resource resource1 = new ClassPathResource("application.yml");
        // 从io流中下载
        // Resource resource2 = new InputStreamResource(null);
        // 从url中下载
        Resource resource3 = new UrlResource("http://47.108.254.101:9000/test/upload/649a4ac67a92945cce11f3a1.json");
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + resource3.getFilename());
        return ResponseEntity.ok()
                .headers(headers)
                .body(resource3);
    }
}
posted @ 2021-07-14 23:15  黄河大道东  阅读(48)  评论(0编辑  收藏  举报