zhuangjie
ZhuangJie

UploadPathHelper

package com.helper;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.io.FileNotFoundException;

@Component
public class UploadPathHelper {
    @Value("${current-jar.value:false}")
    private boolean currentJar;

    @Value("${current-jar.upload-path:C:/mianshi}")
    private String uploadPath;

    public String getUploadPath() throws FileNotFoundException {
        if (currentJar) {
            return uploadPath + "/";
        } else {
            File path = new File(ResourceUtils.getURL("classpath:static").getPath());
            if (!path.exists()) {
                path = new File("");
            }
            return path.getAbsolutePath() + "/upload/";
        }
    }
}

 

FileController

package com.controller;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

import com.helper.UploadPathHelper;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.annotation.IgnoreAuth;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.entity.ConfigEntity;
import com.entity.EIException;
import com.service.ConfigService;
import com.utils.R;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.validation.Valid;

/**
 * 上传文件映射表
 */
@RestController
@RequestMapping("file")
@SuppressWarnings({"unchecked", "rawtypes"})
public class FileController implements WebMvcConfigurer {
    @Autowired
    private ConfigService configService;

    @Autowired
    private UploadPathHelper uploadPathHelper;

    /**
     * 上传文件
     */
    @RequestMapping("/upload")
    @IgnoreAuth
    public R upload(@RequestParam("file") MultipartFile file, String type) throws Exception {
        if (file.isEmpty()) {
            throw new EIException("上传文件不能为空");
        }
        String fileExt = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
//        File path = new File(ResourceUtils.getURL("classpath:static").getPath());
//        if(!path.exists()) {
//            path = new File("");
//        }
        File upload = new File(uploadPathHelper.getUploadPath());
        if (!upload.exists()) {
            upload.mkdirs();
        }
        String fileName = new Date().getTime() + "." + fileExt;
        if (StringUtils.isNotBlank(type) && type.contains("_template")) {
            fileName = type + "." + fileExt;
            new File(upload.getAbsolutePath() + "/" + fileName).deleteOnExit();
        }
        File dest = new File(upload.getAbsolutePath() + "/" + fileName);
        file.transferTo(dest);
        if (StringUtils.isNotBlank(type) && type.equals("1")) {
            ConfigEntity configEntity = configService.selectOne(new EntityWrapper<ConfigEntity>().eq("name", "faceFile"));
            if (configEntity == null) {
                configEntity = new ConfigEntity();
                configEntity.setName("faceFile");
                configEntity.setValue(fileName);
            } else {
                configEntity.setValue(fileName);
            }
            configService.insertOrUpdate(configEntity);
        }
        return R.ok().put("file", fileName);
    }

    /**
     * 下载文件
     */
    @IgnoreAuth
    @RequestMapping("/download")
    public ResponseEntity<byte[]> download(@RequestParam String fileName) {
        try {
            File upload = new File(uploadPathHelper.getUploadPath());
            if (!upload.exists()) {
                upload.mkdirs();
            }
            File file = new File(upload.getAbsolutePath() + "/" + fileName);
            if (file.exists()) {
                /*if(!fileService.canRead(file, SessionManager.getSessionUser())){
                    getResponse().sendError(403);
                }*/
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
                headers.setContentDispositionFormData("attachment", fileName);
                return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new ResponseEntity<byte[]>(HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

 

静态资源映射:

package com.config;

import com.helper.UploadPathHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ResourceUtils;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import com.interceptor.AuthorizationInterceptor;

import java.io.File;
import java.io.FileNotFoundException;

@Configuration
public class InterceptorConfig extends WebMvcConfigurationSupport {

    @Autowired
    private UploadPathHelper uploadPathHelper;

    @Bean
    public AuthorizationInterceptor getAuthorizationInterceptor() {
        return new AuthorizationInterceptor();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(getAuthorizationInterceptor()).addPathPatterns("/**").excludePathPatterns("/static/**");
        super.addInterceptors(registry);
    }

    /**
     * springboot 2.0配置WebMvcConfigurationSupport之后,会导致默认配置被覆盖,要访问静态资源需要重写addResourceHandlers方法
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        try {
            registry.addResourceHandler("/upload/**")
                    .addResourceLocations("file:" + uploadPathHelper.getUploadPath());
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }

        registry.addResourceHandler("/**")
                .addResourceLocations("classpath:/resources/")
                .addResourceLocations("classpath:/static/")
                .addResourceLocations("classpath:/admin/")
                .addResourceLocations("classpath:/front/")
                .addResourceLocations("classpath:/front-pc/")
                .addResourceLocations("classpath:/public/");
        super.addResourceHandlers(registry);
    }


}

 

配置:

current: 

   value: true

 upload-path: D:/a/b/c

package com.helper;
import org.springframework.beans.factory.annotation.Value;import org.springframework.stereotype.Component;import org.springframework.util.ResourceUtils;
import java.io.File;import java.io.FileNotFoundException;
@Componentpublic class UploadPathHelper {    @Value("${current-jar.value:false}")    private boolean currentJar;
    @Value("${current-jar.upload-path:C:/mianshi}")    private String uploadPath;
    public String getUploadPath() throws FileNotFoundException {        if (currentJar) {            return uploadPath + "/";        } else {            File path = new File(ResourceUtils.getURL("classpath:static").getPath());            if (!path.exists()) {                path = new File("");            }            return path.getAbsolutePath() + "/upload/";        }    }}



package com.controller;
import java.io.File;import java.io.FileNotFoundException;import java.io.IOException;import java.util.Arrays;import java.util.Date;import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.Random;import java.util.UUID;
import com.helper.UploadPathHelper;import org.apache.commons.io.FileUtils;import org.apache.commons.lang3.StringUtils;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Value;import org.springframework.http.HttpHeaders;import org.springframework.http.HttpStatus;import org.springframework.http.MediaType;import org.springframework.http.ResponseEntity;import org.springframework.util.ResourceUtils;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.RestController;import org.springframework.web.multipart.MultipartFile;
import com.annotation.IgnoreAuth;import com.baomidou.mybatisplus.mapper.EntityWrapper;import com.entity.ConfigEntity;import com.entity.EIException;import com.service.ConfigService;import com.utils.R;import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import javax.validation.Valid;
/** * 上传文件映射表 */@RestController@RequestMapping("file")@SuppressWarnings({"unchecked", "rawtypes"})public class FileController implements WebMvcConfigurer {    @Autowired    private ConfigService configService;
    @Autowired    private UploadPathHelper uploadPathHelper;
    /**     * 上传文件     */    @RequestMapping("/upload")    @IgnoreAuth    public R upload(@RequestParam("file") MultipartFile file, String type) throws Exception {        if (file.isEmpty()) {            throw new EIException("上传文件不能为空");        }        String fileExt = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);//File path = new File(ResourceUtils.getURL("classpath:static").getPath());//if(!path.exists()) {//    path = new File("");//}        File upload = new File(uploadPathHelper.getUploadPath());        if (!upload.exists()) {            upload.mkdirs();        }        String fileName = new Date().getTime() + "." + fileExt;        if (StringUtils.isNotBlank(type) && type.contains("_template")) {            fileName = type + "." + fileExt;            new File(upload.getAbsolutePath() + "/" + fileName).deleteOnExit();        }        File dest = new File(upload.getAbsolutePath() + "/" + fileName);        file.transferTo(dest);        if (StringUtils.isNotBlank(type) && type.equals("1")) {            ConfigEntity configEntity = configService.selectOne(new EntityWrapper<ConfigEntity>().eq("name", "faceFile"));            if (configEntity == null) {                configEntity = new ConfigEntity();                configEntity.setName("faceFile");                configEntity.setValue(fileName);            } else {                configEntity.setValue(fileName);            }            configService.insertOrUpdate(configEntity);        }        return R.ok().put("file", fileName);    }
    /**     * 下载文件     */    @IgnoreAuth    @RequestMapping("/download")    public ResponseEntity<byte[]> download(@RequestParam String fileName) {        try {            File upload = new File(uploadPathHelper.getUploadPath());            if (!upload.exists()) {                upload.mkdirs();            }            File file = new File(upload.getAbsolutePath() + "/" + fileName);            if (file.exists()) {/*if(!fileService.canRead(file, SessionManager.getSessionUser())){getResponse().sendError(403);}*/                HttpHeaders headers = new HttpHeaders();                headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);                headers.setContentDispositionFormData("attachment", fileName);                return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);            }        } catch (IOException e) {            e.printStackTrace();        }        return new ResponseEntity<byte[]>(HttpStatus.INTERNAL_SERVER_ERROR);    }}


package com.config;
import com.helper.UploadPathHelper;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Value;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.util.ResourceUtils;import org.springframework.web.servlet.config.annotation.InterceptorRegistry;import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import com.interceptor.AuthorizationInterceptor;
import java.io.File;import java.io.FileNotFoundException;
@Configurationpublic class InterceptorConfig extends WebMvcConfigurationSupport {
    @Autowired    private UploadPathHelper uploadPathHelper;
    @Bean    public AuthorizationInterceptor getAuthorizationInterceptor() {        return new AuthorizationInterceptor();    }
    @Override    public void addInterceptors(InterceptorRegistry registry) {        registry.addInterceptor(getAuthorizationInterceptor()).addPathPatterns("/**").excludePathPatterns("/static/**");        super.addInterceptors(registry);    }
    /**     * springboot 2.0配置WebMvcConfigurationSupport之后,会导致默认配置被覆盖,要访问静态资源需要重写addResourceHandlers方法     */    @Override    public void addResourceHandlers(ResourceHandlerRegistry registry) {        try {            registry.addResourceHandler("/upload/**")                    .addResourceLocations("file:" + uploadPathHelper.getUploadPath());        } catch (FileNotFoundException e) {            throw new RuntimeException(e);        }
        registry.addResourceHandler("/**")                .addResourceLocations("classpath:/resources/")                .addResourceLocations("classpath:/static/")                .addResourceLocations("classpath:/admin/")                .addResourceLocations("classpath:/front/")                .addResourceLocations("classpath:/front-pc/")                .addResourceLocations("classpath:/public/");        super.addResourceHandlers(registry);    }

}
 
posted on 2025-05-17 11:32  zhuangjie  阅读(7)  评论(0)    收藏  举报