spring boot图片上传至远程服务器并返回新的图片路径

界面上传图片时考虑到可能会有用户的图片名称一致,使用UUID来对图片名称进行重新生成。

//UUIDUtils

public class UUIDUtils {
    public static String getUUID(){
        return UUID.randomUUID().toString().replace("-", "");
    }
}

//FileNameUtil

//生成新的文件名
public class FileNameUtil {
    /**
     * 获取文件后缀
     * @param fileName
     * @return
     */
    public static String getSuffix(String fileName){
        return fileName.substring(fileName.lastIndexOf("."));
    }

    /**
     * 生成新的文件名
     * @param fileOriginName 源文件名
     * @return
     */
    public static String getFileName(String fileOriginName){
        return UUIDUtils.getUUID() + FileNameUtil.getSuffix(fileOriginName);
    }

}
View Code

//FileUploadUtil

//图片上传工具类
public class FileUploadUtil {
    /**
     * 
     * @param file 文件
     * @param path   文件存放路径
     * @param fileName 原文件名
     * @return
     */
     public static boolean upload(MultipartFile file, String path, String fileName){

            // 生成新的文件名
            String realPath = path + "/" +fileName;

            //使用原文件名
           // String realPath = path + "/" + fileName;

            File dest = new File(realPath);

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

            try {
                //保存文件
                file.transferTo(dest);
                return true;
            } catch (IllegalStateException e) {             
                e.printStackTrace();
                return false;
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            }

        }

}
View Code

//application.properties

# 设置单个文件最大内存
spring.servlet.multipart.max-file-size = 50Mb 
# 设置所有文件最大内存
spring.http.multipart.max-request-size=500Mb 
# 自定义文件上传路径
web.upload-path=F:/blog-images/

在这里,由于我将图片上传至自己的本地服务器上了,而本地的磁盘都是被保护的,无法直接访问他,所以我需要给我的图片一个虚拟路径,将虚拟路径映射到此图片存放位置即可

写一个配置类uploadFileConfig

@Configuration
public class UploadFileConfig extends WebMvcConfigurationSupport {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry){
        registry.addResourceHandler("/images/**").addResourceLocations("file:/F:/blog-images/");
        super.addResourceHandlers(registry);
        
    }

}

之后写Controller

    @ApiOperation("图片上传")
    @ApiImplicitParam(name = "file", value = "文件", required = true, dataType = "File")
    @RequestMapping(value="/upload",method= {RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public Result upload(@RequestParam("file")MultipartFile file,HttpServletRequest request) {
        //定义要上传文件 的存放路径
        String localPath="F:/blog-images/";
        //获得文件名字
        String fileName=file.getOriginalFilename();
        fileName= FileNameUtil.getFileName(fileName);
        File dest = new File(localPath + fileName);
        if(FileUploadUtil.upload(file, localPath, fileName)){
            // 将上传的文件写入到服务器端文件夹
            // 获取当前项目运气的完整url
            String requestURL = request.getRequestURL().toString();
            // 获取当前项目的请求路径url
            String requestURI = request.getRequestURI();
            // 得到去掉了uri的路径
            String url = requestURL.substring(0, requestURL.length()-requestURI.length() + 1);
            url="images/"+ fileName;

            
            return  ResultUtil.success(url);

        }       
        // 返回
        return ResultUtil.error(202,"未知错误导致上传失败");
    }
View Code

自此图片上传就成功啦,可以用postman来测试下接口

spring boot图片上传至远程服务器并返回新的图片路径

OK,大功告成。

相关推荐