文件上传 Window & Linux

1. 在application配置文件添加图片存储路径的参数
 上传路径前必须加 file:/ 否则网页图片请求可能404
window

gofy:
  uploadPath: file:/F:/fileUpload/
  imagesPath: F:/fileUpload/
  imagesUrl: http://localhost:8888/images/


linux(在根目类home下的fileUpload文件夹):

gofy:
  uploadPath: file:/home/fileUpload/
  imagesPath: /home/fileUpload/
  imagesUrl: http://域名/images/


2. 添加文件上传配置类

/**
 * 上传配置类
 * 图片放到/F:/fileUpload/后,从磁盘读取的图片数据scr将会变成images/picturename.jpg的格式
 */
@Configuration
public class UploadConfig implements WebMvcConfigurer {

    /**
     * 在配置文件中配置的文件保存路径
     */
    @Value("${gofy.uploadPath}")
    private String uploadPath;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        if(uploadPath.equals("") || uploadPath.equals("${gofy.imagesPath}")){
            String imagesPath = WebMvcConfig.class.getClassLoader().getResource("").getPath();
            System.out.print("1.上传配置类imagesPath=="+imagesPath+"\n");
            if(imagesPath.indexOf(".jar")>0){
                imagesPath = imagesPath.substring(0, imagesPath.indexOf(".jar"));
            }else if(imagesPath.indexOf("classes")>0){
                imagesPath = "file:"+imagesPath.substring(0, imagesPath.indexOf("classes"));
            }
            imagesPath = imagesPath.substring(0, imagesPath.lastIndexOf("/"))+"/images/";
            uploadPath = imagesPath;
        }
        //System.out.print("imagesPath============="+mImagesPath+"\n");
        //LoggerFactory.getLogger(WebAppConfig.class).info("imagesPath============="+mImagesPath+"\n");
        registry.addResourceHandler("/images/**").addResourceLocations(uploadPath);
        // TODO Auto-generated method stub
        //System.out.print("2.上传配置类mImagesPath=="+mImagesPath+"\n");

        WebMvcConfigurer.super.addResourceHandlers(registry);
    }
}



3. 添加文件上传的工具类
数据库最好储存动态路径和绝对路径,动态路径用于项目使用,绝对路径便于文件删除

/**
 * 文件上传工具类
 */
@Component
public class UploadUtil {

    @Value("${gofy.imagesPath}")
    private String imagesPath;
    @Value("${gofy.imagesUrl}")
    private String imagesUrl;
    /**
     * 返回文件保存的路径
     * @param file
     * @return
     */
    private String url;
    public Map getFileUrl(MultipartFile file){
        Map<String,String> map = new HashMap<String,String>();
        System.out.println("上传文件===");
        //判断文件是否为空
        if(file.isEmpty()){
            map.put("error","文件不能为空");
            return map;
        }

        //获取文件名
        String fileName = file.getOriginalFilename();
        System.out.println("上传的文件名为:"+fileName);
        //加个时间戳,尽量避免文件名称重复
        fileName= new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + "_" + fileName;
        System.out.println("(加个时间戳,尽量避免文件名称重复)保存的文件名为: "+fileName);

        //文件绝对路径
        String path = imagesPath+fileName;
        System.out.println("保存文件的绝对路径"+path);

        //创建文件路径
        File dest = new File(path);

        //判断文件父目类是否存在
        if(!dest.getParentFile().exists()){
            dest.getParentFile().mkdir();
        }

        try{
            //上传文件
            file.transferTo(dest);//保存文件
            System.out.println("保存文件路径"+path);
            url = imagesUrl+fileName;
            System.out.println("保存的完整url==="+url);
        }catch (IOException e){
            e.printStackTrace();
            map.put("error","上传失败");
            return map;
        }
        map.put("url",url);
        map.put("path",path);
        return map;
    }
}

我的个人博客

www.gofy.top

猜你喜欢

转载自www.cnblogs.com/gaofei200/p/12584781.html