关于文件上传,下载

配置文件

#uploadFolder 是上传路径,如果部署在linux,把路径改为linux下的
file.uploadFolder=D:/upload/
file.staticAccessPath=/a/file/**

spring.servlet.multipart.enabled=true
#最大上传文件总体积
spring.servlet.multipart.max-request-size=100MB
#当上传多大时,写入硬盘
spring.servlet.multipart.file-size-threshold=1MB
#单个文件最大的体积
spring.servlet.multipart.max-file-size=10MB

1.配置本地路径可以被外网访问


@Configuration
public class UploadFilePathConfig implements WebMvcConfigurer {

    @Value("${file.staticAccessPath}")
    private String staticAccessPath;

    @Value("${file.uploadFolder}")
    private String uploadFolder;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
                    
  registry.addResourceHandler(staticAccessPath).addResourceLocations("file:"+uploadFolder);
    }
}

2.文件上传

 @Value("${file.uploadFolder}")
    private String uploadFolder;

@RequestMapping("fileUpload")
    @ResponseBody
    public void fileUpload(MultipartFile file){
        try{
            String filepath = uploadFolder;
            File fsupload = new File(filepath);
            if(!fsupload.exists()){
                fsupload.mkdirs();
            }
            //将文件名改成uuid的形式
            //定义新的文件名
            String fileid = UUID.randomUUID().toString();
            String ext = FilenameUtils.getExtension(file.getOriginalFilename());
            File newUploadFile = new File(filepath,fileid+"."+ext);

            //将上传的文件,按指定的名称保存到指定的路径下
            file.transferTo(newUploadFile);

        }catch (Exception e){
            e.printStackTrace();
        }
    }

3.文件下载

@RequestMapping("fileDownload")
    @ResponseBody
    public void fileDownload(String filename,HttpServletResponse response){
        try{
            String filePath = uploadFolder;

            File file = new File(filePath+File.separator+filename);
            if(file.exists()){
                response.setHeader("Content-Type","application/octet-stream;charset=utf-8");
                response.setHeader("Content-Disposition","attachment;filename="+
                        new String("图书信息统计表.xlsx".getBytes(StandardCharsets.UTF_8),"ISO8859-1"));
                byte []buffer = new byte[1024];
                FileInputStream fis = new FileInputStream(file);
                OutputStream os = response.getOutputStream();

                int i=0;
                while((i=fis.read(buffer))!=-1){
                    os.write(buffer,0,i);
                }

            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值