springboot上传图片,配置虚拟路径提供前端访问

最近在做springboot项目的时候,需要上传图片并且提供URL给前端。废话不多说,直接上代码。

1.首先在application.yml配置中添加如下配置


 ###服务启动端口号
server:
  port: 8003
  tomcat:
    uri-encoding: UTF-8
###文件上传
file:
  ###静态资源对外暴露的访问路径
  staticAccessPath: /api/file/**
  ###静态资源实际存储路径
  uploadFolder: F:/upload/mall/
  uploadImage: image/
###项目名
  servlet:
     context-path:
     ###文件上传
     multipart:
     enabled: true
     max-file-size: 10mb
     max-request-size: 10mb
###服务名称(服务注册到eureka名称)  
spring:
    application:
        name: test
    mvc:
        throw-exception-if-no-handler-found: true
        static-path-pattern: /**
    #静态资源访问
    resources:
        add-mappings: true
        static-locations: classpath\:/META-INF/resources/,classpath\:/resources/,classpath\:/static/,classpath\:/public/,file\:${file.uploadFolder}${file.uploadImage}
    http:
        encoding:
            force: true
            charset: utf-8
            enabled: true


2.然后新建一个类,继承WebMvcConfigurerAdapter

 


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.WebMvcConfigurerAdapter;
 
@SuppressWarnings("deprecation")
@Configuration
public class UploadFilePathConfig extends WebMvcConfigurerAdapter{
    
    @Value("${file.staticAccessPath}")
    private String staticAccessPath;
    @Value("${file.uploadFolder}")
    private String uploadFolder;
    @Value("${file.uploadImage}")
    private String uploadImage;
 
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler(staticAccessPath).addResourceLocations("file:///" + uploadFolder + uploadImage);
        super.addResourceHandlers(registry);
    }
 
}


3.接着编写controller类


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
 
import com.alibaba.fastjson.JSONObject;
import com.snimay.entity.RetStruct;
import com.snimay.utils.FileUpload;
import com.snimay.utils.exception.MallException;
import com.snimay.utils.map.MapUtil;
 
@Controller
@RequestMapping("/fileupload/")
public class FileUploadController {
    
    //获取主机端口
    @Value("${server.port}")
    private String POST;
    //静态资源对外暴露的访问路径
    @Value("${file.staticAccessPath}")
    private String staticAccessPath;
    //实际存储路径
    @Value("${file.uploadFolder}")
    private String uploadFolder;
    //图片
    @Value("${file.uploadImage}")
    private String uploadImage;
 
    /**
     * 获取所有文件上传前缀路径
     *
     * @param file
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "getSourceUrl.do", produces = "text/html;charset=UTF-8")
    public String getPrefixPath(HttpServletRequest request, HttpServletResponse response) {
        JSONObject resultObj = new JSONObject();
        JSONObject dataObj = new JSONObject();
        String fileUploadBackUrl = FileUpload.fileUploadBackUrl;
        dataObj.put("sourceUrl", fileUploadBackUrl + FileUpload.sourceDir);
        resultObj.put("code", 0);
        resultObj.put("msg", "获取所有路径成功");
        resultObj.put("data", dataObj);
        return resultObj.toString();
    }
    
    /**
     * Description: 上传名片图片
     *
     * @param request
     * @param response
     * @return
     */
    @SuppressWarnings("unchecked")
    @ResponseBody
    @RequestMapping(value = "uploadBusinessCardImage.do", produces = "text/html;charset=UTF-8")
    public String uploadBusinessCardImage(@RequestParam("file") MultipartFile file) {
        try {
            if (file.isEmpty()) {
                throw new MallException(-1,"上传文件为空");
            }
            
            String originalFilename = file.getOriginalFilename();
            String result = FileUpload.FileUpLoadAndGetParam(file, POST, staticAccessPath, uploadFolder, uploadImage, originalFilename);
            Map<String, Object> resultMap = JSONObject.parseObject(result.trim());
            Map<String, Object> layeditMap = new HashMap<>();
            if (resultMap.get("code").equals(0)) {
                Map<String, Object> resultDataMap = (Map<String, Object>) resultMap.get("data");System.out.println(resultDataMap);
                layeditMap.put("src", resultDataMap.get("http_url"));
                layeditMap.put("title", resultDataMap.get("file_name"));
                resultMap.put("data", layeditMap);
                resultMap.remove("param");
 
                result = resultMap.toString();
            }
            return result;
        } catch (Exception e) {
            return new RetStruct(-1, e.getMessage()).toString();
        }
    }
 
 
}


4.上传文件的工具类,最后返回结果封装为json格式

public class FileUpload {
    private static final Logger log = LoggerFactory.getLogger(FileUpload.class);
    public static String FILES_TYPE;
    public static String IMG_TYPE;
    public static int UPLOAD_MAX_SIZE;
    public static long UPLOAD_MAX_SIZE_BYTE;
 
    private Map<String, String> params;
    private Map<String, Object> mFilesUrlJSON = new HashMap<>();
    private static long fileSize = 0;
    private String errStr = "";
 
    static {
        InputStream is = null;
        try {
            Properties pro = new Properties();
            is = FileUpload.class.getResourceAsStream("/config.properties");
            pro.load(is);
            FILES_TYPE = FileType.getAllName();
            IMG_TYPE = ImgType.getAllName();
            UPLOAD_MAX_SIZE = pro.getProperty("uploadMaxSize") == null ? 2
                    : Integer.parseInt(pro.getProperty("uploadMaxSize"));
            UPLOAD_MAX_SIZE_BYTE = UPLOAD_MAX_SIZE * 1024 * 1024;
            is.close();
        } catch (IOException e) {
            ILogUtil.info(e.getMessage());
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e1) {
                    ILogUtil.info("关闭流出错.");
                }
            }
        }
    }
    
    /**
     * Description:
     * @param file 文件对象
     * @param POST 端口号
     * @param staticAccessPath 对外显示路径
     * @param uploadFolder 上传文件夹的主路径
     * @param filePath 上传文件的文件夹路径
     * @param originalFilename 原始文件名称
     * @return
     */
    public static String FileUpLoadAndGetParam(MultipartFile file, String POST, String staticAccessPath,
            String uploadFolder, String filePath, String originalFilename) {
        FileUpload fu = new FileUpload();
        if (!fu.writeFile(file, POST, staticAccessPath, uploadFolder, filePath, originalFilename)) {
            return RetResponse(10, "写文件失败," + fu.getErrStr());
        }
        JSONObject obj = fu.getFilesUrlJson();
        JSONObject json = new JSONObject();
        json.put("code", 0);
        json.put("msg", "上传成功");
        json.put("data", obj);
        json.put("param", fu.getParamsJson());
        return json.toString();
    }
    
    private boolean writeFile(MultipartFile file, String POST, String staticAccessPath,
            String uploadFolder,String filePath, String originalFilename) {
        fileSize = file.getSize();
        File fileExists = new File(uploadFolder + filePath);
        
        try {
            if (!fileExists.exists()) {
                fileExists.mkdirs();
            }
        } catch (Exception e) {
            ILogUtil.info(e.getMessage());
            return false;
        }
        
        String oldFileName = originalFilename;
        if (!checkFile(oldFileName, FILES_TYPE)) {
            errStr = "校验文件类型失败,系统支持格式:" + FILES_TYPE;
            ILogUtil.info("校验文件类型失败");
            return false;
        }
        
        // 不是所有的上传文件都有扩展名,需要允许上传的文件没有扩展名
        String suffix = "";
        int index = oldFileName.lastIndexOf(".");
        if (index != -1) {
            suffix = oldFileName.substring(index);
        }
        
        // 生成随机名称
        String fileName = UUIDUtils.getUUID(16) + suffix;
 
        mFilesUrlJSON.put("http_url", saveUploadFileVirtualUrl(POST, staticAccessPath) + fileName);
        mFilesUrlJSON.put("file_name", fileName);
        mFilesUrlJSON.put("server_url", saveUploadFileVirtualUrl(POST, staticAccessPath));
        mFilesUrlJSON.put("path", "/" + filePath + fileName);// 存储的目录
        mFilesUrlJSON.put("file_size", fileSize);
        mFilesUrlJSON.put("suffix", suffix);
        mFilesUrlJSON.put("old_file_name", oldFileName);
        File newFile = new File(uploadFolder + filePath, fileName);
        
        try {
            file.transferTo(newFile);
        } catch (Exception e) {
            errStr = e.getMessage();
            ILogUtil.info(e.getMessage());
            return false;
        }
        
        return true;
    }
    
    /**
     * Description: 获取服务器地址,拼接虚拟路径
     * @return
     */
    private String saveUploadFileVirtualUrl(String POST, String staticAccessPath) {
        //获取本机IP
        String host = null;
        try {
            host = InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            ILogUtil.error("get server host Exception e:", e);
        }
        String virtual_url = host + ":" + POST + staticAccessPath.substring(0, staticAccessPath.length()-2);
        return virtual_url;
    }
 
    private boolean checkFile(String fileName, String filesType) {
        // 获取文件后缀
        if (filesType == null) {
            // 不校验
            return true;
        }
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
        if (filesType.contains(suffix.trim().toLowerCase())) {
            return true;
        }
        return false;
    }
 
 
    private Object getParamsJson() {
        return (JSONObject) JSONObject.toJSON(params);
    }
 
    private JSONObject getFilesUrlJson() {
        return JSONObject.parseObject(JSON.toJSONString(mFilesUrlJSON));
    }
 
    private String getErrStr() {
        return errStr;
    }
    
    public static String RetResponse(int code, String msg) {
        JSONObject obj = new JSONObject();
        obj.put("code", code);
        obj.put("msg", msg);
        return obj.toString();
    }
 
    
 
}
 


5.最后是生成随机数的工具类


import java.util.UUID;
 
public class UUIDUtils {
 
    public static String getUUID() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }
 
    public static String getUUID(Integer len) {
        return UUID.randomUUID().toString().replaceAll("-", "").substring(0, len);
    }
}


 

6.用postman进行测试



作者:wzn1054162229
来源:CSDN
原文:https://blog.csdn.net/wzn1054162229/article/details/90731392



 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot 配置虚拟路径主要是为了在应用中处理非根目录的静态资源访问,比如当你的静态资源文件(如HTML、CSS、JS等)位于项目的子目录或非根目录时,如何使其能够被浏览器直接访问。以下是如何在 Spring Boot配置虚拟路径: 1. **使用`static`前缀**:Spring Boot 自带了对静态资源的支持,你可以在 `src/main/resources/static` 目录下放置你的静态文件,并在 WebMvc 配置中使用 `spring.mvc.static-path-pattern` 或 `spring.resources.static-locations` 配置虚拟路径。例如: ```yaml spring: mvc: static-path-pattern: /webapp/** ``` 这样,当你访问 `/webapp/filename.html` 时,Spring Boot 将自动查找 `src/main/resources/webapp/filename.html`。 2. **自定义ResourceHandler**:如果需要更复杂的路径映射,可以通过自定义 `ResourceHttpRequestHandler`,并添加到 `WebMvcConfigurer` 中来实现: ```java @Bean public ResourceHttpRequestHandler resourceHttpRequestHandler() { return new ResourceHttpRequestHandler(new ClassPathResource("webapp")); } ``` 这里,`ClassPathResource` 指定静态资源所在的目录。 3. **使用`Thymeleaf`或`Freemarker`模板引擎**:如果你使用了模板引擎(如 Thymeleaf 或 Freemarker),它们有自己的机制处理静态资源,可能需要额外配置。 相关问题: 1. Spring Boot 如何处理来自非根目录的静态资源请求? 2. 如何在 Spring Boot配置自定义的静态资源处理器? 3. 使用模板引擎处理静态资源时,是否还需要额外的配置
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值