application.yml

#上传文件的路径和映射地址
#本地存放路径
localFileUrl: D:\down
#映射的网络url
mappingFileUrl: /static/
#ip访问本地文件
hostFileUrl: http://localhost:8092/static/

MyWebAppConfiguration

package com.cei.xyd_cz.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import com.cei.xyd_cz.Interceptor.XYDInterceptor;

@Configuration
public class MyWebAppConfiguration extends WebMvcConfigurerAdapter {

	@Value("${localFileUrl}")
	private String localFileUrl;//本地存放的文件路径 例如:E:\down
	@Value("${mappingFileUrl}")
	private String mappingFileUrl;//映射的虚拟网络地址  供页面连接访问的url

	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {

		registry.addResourceHandler(mappingFileUrl+"**").addResourceLocations("file:"+localFileUrl+"/");
	}

}

接口

Result返回类型是我自己封装的,自己换自己的

 @Value("${localFileUrl}")
    private String path;

 @Value("${hostFileUrl}")
    private String hostPath;
/**
     * 产品上传Logo
     *
     * @param file
     * @return
     * @throws FileNotFoundException
     */
    @PostMapping("/uploadProductFile")
    @ResponseBody
    public Result uploadProductFile(@RequestParam("file") MultipartFile file) throws FileNotFoundException {
        Result res = new Result();
        Map<String, Object> map = new HashMap<>();
        try {
            String dateName = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
            String date = new SimpleDateFormat("yyyyMMdd").format(new Date());
            String fileName = file.getOriginalFilename();
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            String filePath = path + "/";
//        fileName = dateName + suffixName;
            fileName = dateName + "-" + fileName;
            File dest = new File(filePath + fileName);
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            try {
                file.transferTo(dest);
                map.put("filePath", hostPath + fileName);
                return ResultGenerator.genSuccessResult(map);
            } catch (IOException e) {
                System.out.println(e);
            }
            return ResultGenerator.genFailResult("上传失败");
        } catch (Exception e) {
            return ResultGenerator.genFailResult(e.getMessage());
        }
    }

 部署的时候别忘了改下application的配置地址,改成线上地址

 接口最后拼的filepath就是实际链接地址,直接点就能取到文件,存到库里返给前台看实际业务需求

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐