Java文件上传及下载

▶SpringBoot集成文件 - 基础的文件上传和下载 | Java 全栈知识体系

1.文件上传

@RestController
@RequestMapping("/file")
public class upload {
    @PostMapping("/upload")
    public String  upload(@RequestParam(value = "file", required = true) MultipartFile file) {
        try {
            // 本地文件保存位置
            String uploadPath = "E:\\upload"; // 改这里
            File uploadDir = new File(uploadPath);
            if (!uploadDir.exists()) {
                uploadDir.mkdir();
            }
            System.out.println(uploadDir.getAbsolutePath());
            // 本地文件
            File localFile = new File(uploadPath + File.separator + file.getOriginalFilename());
            // transfer to local
            file.transferTo(localFile);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
        }
        return "sucessfully";
    }
}

 

file.transferTo(localFile)方法的作用是将文件从源位置传输到本地目标文件中。

file.transferTo()方法是MultipartFile接口的默认实现,它会使用IO流的方式将上传的文件保存到指定的本地文件。因此,您不需要进行额外的IO流操作。

@RestController
@RequestMapping("/file")
public class upload {
    @PostMapping("/upload")
    public String  upload(@RequestParam(value = "file", required = true) MultipartFile file) {
        try {
            String uploadPath = "E:\\upload";
            File uploadDir = new File(uploadPath);
            if (!uploadDir.exists()) {
                uploadDir.mkdir();
            }
            System.out.println(uploadDir.getAbsolutePath());
            // 本地文件
            File localFile = new File(uploadPath + File.separator + file.getOriginalFilename());
            try (InputStream inputStream = file.getInputStream();
                 OutputStream outputStream = new FileOutputStream(localFile)) {

                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
        }
        return "sucessfully";
    }
}

 2.文件下载

@GetMapping("/download")
public void download(HttpServletResponse response) {
    response.reset();
    response.setContentType("application/octet-stream");
    response.setHeader("Content-disposition",
            "attachment;filename=file_" + System.currentTimeMillis() + ".hprof");

    // 从文件读到servlet response输出流中
    File file = new File("/Users/pdai/pdai_heap_dump_test.hprof"); // 改这里
    try (FileInputStream inputStream &
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值