springboot文件上传下载

本文详细介绍了一个基于SpringBoot的文件控制器实现,演示了如何使用MultipartFile进行文件上传,并通过HTTP GET请求实现文件下载。文章提供了完整的代码示例,包括使用postman进行测试的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.example.springboot.controller;

import com.example.springboot.entity.FileInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import sun.nio.ch.IOUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * 文件上传下载
 */
@Slf4j
@RestController
@RequestMapping("/file")
public class FileController {

    private String dizhi="D:\\My_Java\\anli\\springboot\\src\\main\\java\\com\\example\\springboot\\controller";


    /**
     * 上传
     *
     * postman测试
     * http://localhost:8083/file
     * body  form-data
     * key: value:
     * @param file
     * @return
     */
    @PostMapping
    public FileInfo upload(MultipartFile file) throws Exception{

        System.out.println(file.getName());
        System.out.println(file.getOriginalFilename());
        System.out.println(file.getSize());
        File bendiFile = new File(dizhi,System.currentTimeMillis()+".txt");
        //把传上来的文件写到本地文件
        file.transferTo(bendiFile);
        //绝对路径
        return new FileInfo(bendiFile.getAbsolutePath());
    }
    /**
     * 下载
     * http://localhost:8083/file/1546167484107
     */
    @GetMapping("/{id}")
    public void download(@PathVariable String id, HttpServletRequest request, HttpServletResponse response)
    {
         try(
                 //读文件
                 InputStream inputStream = new FileInputStream(new File(dizhi,id+".txt"));
                 //写
                 OutputStream outputStream =response.getOutputStream();

                 ) {
             response.setContentType("application/x-download");
             response.addHeader("Contend-Disposition","attachment;filename=test.txt");
            //copy
             IOUtils.copy(inputStream,outputStream);
             outputStream.flush();


         }catch (Exception e){

         }
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值