SpringBoot 实现文件上传访问

哈喽,大家好,我是程序猿小张。本文章通过Spring Boot 实现文件的上传与访问
话不多说,直接上代码~

一、yml文件配置

spring:
  resources:
    static-locations: classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,file:${web.upload-path}```

#本机或服务器的地址,指向上传的目录
file:
  uploadFolder: D:/data/

#本机或服务器的地址,指向访问的文件目录
web:
  upload-path: D:/data/

注意:需要在static-locations后面添加文件访问地址

二、文件上传与下载接口

此处type用于控制文件访问权限(基于security,是否需要登录),如果需要可查看文章

Java 基于Spring Security实现文件上传权限控制

    @Resource
    private SysFileService sysFileService;

    @PostMapping("/info")
    @ApiOperation("文件上传")
    public BaseRes<SysFile> uploadFile(@RequestParam(name = "file", required = false) MultipartFile file, @RequestParam("type") Integer type) {
        return sysFileService.uploadFile(file,type);
    }

    @GetMapping("/downFile")
    @ApiOperation("下载文件")
    public void downFile(@RequestParam("id") Integer id) {
        sysFileService.downFile(id);
    }

注意:如果文件是图片可以使用项目地址直接访问

三、实现方法

public BaseRes<SysFile> uploadFile(MultipartFile multipartFile, Integer type) {
        DateFormat df = new SimpleDateFormat("yyyyMMdd");
        String folderName = df.format(new Date());

        String originalFilename = multipartFile.getOriginalFilename();

        // 根据类型获取枚举
        Optional<Constants.UploadFileType> m = EnumUtils.getEnumObject(Constants.UploadFileType.class, e -> Objects.equals(e.code,type));

        Constants.UploadFileType uploadFileType;

        if (Objects.nonNull(m) && m.isPresent()) {
            uploadFileType = m.get();
        }else {
            uploadFileType = Constants.UploadFileType.other;
        }

        String uploadPath = FileUtil.getUploadDate(multipartFile, folderName, uploadFileType);
		// 数据库保存文件信息
        SysFile sysFile = new SysFile();

        sysFile.setName(originalFilename);
        sysFile.setPath(uploadPath);
        sysFile.setSuffix(originalFilename.split("\\.")[1]);

        baseMapper.insert(sysFile);


        return new BaseRes<>(sysFile, ServiceCode.SUCCESS);
    }



    @Override
    public void downFile(Integer id) {
        SysFile sysFile = baseMapper.selectById(id);

        String path = sysFile.getPath();
        String name = sysFile.getName();

        HttpServletResponse response = CommUtils.getResponse();

        try {

            FileInputStream inputStream = new FileInputStream(uploadPath + path);

            InputStream fis = new BufferedInputStream(inputStream);
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();

            CommUtils.setResponseHeader(response, name);
            OutputStream os = response.getOutputStream();
            OutputStream toClient = new BufferedOutputStream(os);
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

四、工具类

1.文件上传FIleUtil

@Component
public class FileUtil {

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

    @PostConstruct
    public void getUploadFolder() {
        fileUpload = this.uploadFolder;
    }

    /**
     * 获取文件上传的数据
     * @param pic1
     * @param images
     * @return
     */
    public static String getUploadDate(MultipartFile pic1, String images, Constants.UploadFileType type) {// images 上传的文件夹
        //如果文件夹不存在则创建
        File file = new File(fileUpload + type.name() + "/" + images);
        if (!file.exists() && !file.isDirectory()) {
            file.mkdirs();
        }
        //获取用户上传文件的后缀名并转换大小写
        String ext1 = FilenameUtils.getExtension(pic1.getOriginalFilename()).toLowerCase();
        DateFormat df = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String format1 = df.format(new Date());
        Random t = new Random();
        for (int i = 0; i < 3; i++) {
            format1 += t.nextInt(10);
        }
        try {
            pic1.transferTo(new File(fileUpload + type.name() +"/" + images + "/" + format1 + "." + ext1));
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
        // 返回文件地址
        return type.name() + "/" + images + "/" + format1 + "." + ext1;
    }
 }

2.CommUtils

public class CommUtils {

	public static HttpServletRequest getRequest() {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		return request;
	}
	
	public static HttpServletResponse getResponse() {
        HttpServletResponse response=((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        return response;
	}

	//以文件流的形式返回
	public static void setResponseHeader(HttpServletResponse response, String fileName) {
		try {
			response.setContentType("application/octet-stream; charset=UTF-8");
			response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
			response.setHeader("content-disposition", "attachment;filename=" + java.net.URLEncoder.encode(fileName, "UTF-8"));
			response.addHeader("Pargam", "no-cache");
			response.addHeader("Cache-Control", "no-cache");
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

}

大功告成啦~,访问http://localhost:port/filePath 即可访问图片

你可能感兴趣的:(Java,Spring,Boot,spring,boot,java,spring)