【SpringBoot】文件上传

一、配置信息

# 与spring 同级
file:
  accessPath: /upfs/ #程序映射路径
  staticAccessPath: /upfs/** #允许的程序映射路径
  uploadFolder: D://temp/ #真实路径

二、配置上传参数

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
@Data
public class FileUploadConfig 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);//在web里添加新的一条文件路径
    }  
}

三、controller部分

@RestController
@CrossOrigin
@RequestMapping("/file")
@SuppressWarnings("unchecked")
public class FileUploadController {

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

    @Resource
    private Environment environment;    

    //文件上传服务
    @PostMapping(value = "/upload")
    @ResponseBody
    @CrossOrigin(origins = "*", maxAge = 3600)
    public List<String> fileUpload(@RequestParam("file") MultipartFile[] files, Integer fullUrl) {
        List<String> result = new ArrayList<>();

        if (files == null || files.length <= 0) {
            return result;
        }
        for (int i = 0; i < files.length; i++) {
            if (files[i].isEmpty()) {
				 return result;
            }
        }

        try {
            return uploadFile(files);
        } catch (Exception e) {}
        
        return result;
    }

    private List<String> uploadFile(MultipartFile[] files) {
        List<String> result=new ArrayList<>();
        //判断文件是否合法
        String fileName="";
        for (int i = 0; i < files.length; i++) {
            fileName = files[i].getOriginalFilename();
            try {
                String url =saveFile(files[i]);
                result.add(url);
            } catch (Exception e) {}
                return result;
            }
        }
        return result;
    }

    private String saveFile(MultipartFile file) throws Exception{
    
        String   fileName = file.getOriginalFilename();
        String fileSuffix = fileName.substring(fileName.lastIndexOf(".") + 1);
        InputStream inputStream = file.getInputStream();
        // 文件唯一的名字
        String newFileName = UUID.randomUUID().toString() + "." + fileSuffix;
        Date todayDate = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String today = dateFormat.format(todayDate);
        // 域名访问的相对路径(通过浏览器访问的链接-虚拟路径)
        String saveToPath = accessPath + today + "/"; // /upfs/2022-04-17/
        // 真实路径,实际储存的路径
        String realPath = realBasePath + today + "/";
        // 储存文件的物理路径,使用本地路径储存
        String filepath = realPath + newFileName;// D://temp/2022-04-17/1.jpg

        // 判断有没有对应的文件夹
        File destFile = new File(filepath);
        if (!destFile.getParentFile().exists()) {
            Boolean b = destFile.getParentFile().mkdirs();
        }

        // 输出流 输出到文件
        OutputStream outputStream = new FileOutputStream(destFile);
        // 缓冲区
        byte[] bs = new byte[1024];
        int len = -1;
        while ((len = inputStream.read(bs)) != -1) {
            outputStream.write(bs, 0, len);
        }
        inputStream.close();
        outputStream.close();
        
        return saveToPath + newFileName;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值