当前位置: 首页>JAVA技术>springmvc/springboot实现上传图片或者文件并返回路径

springmvc/springboot实现上传图片或者文件并返回路径

作者:你好吗 4月前 ⋅ 8743 阅读

  springmvc/springboot经常会用到需要把本地图片上传到网站路径下并返回文件对应的url,如果不上传到OSS,那只能存本地了。

  首先需要配置web对应路径,实现接口WebMvcConfigurer 

import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.mtons.mblog.web.interceptor.BaseInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.*;

import java.util.List;

/**
 * @author likl
 */
@Configuration
public class WebMvcConfiguration implements WebMvcConfigurer {
    @Autowired
    private BaseInterceptor baseInterceptor;
    @Autowired
    private FastJsonHttpMessageConverter fastJsonHttpMessageConverter;
    @Autowired
    private SiteOptions siteOptions;

    /**
     * Add intercepter
     *
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(baseInterceptor)
                .addPathPatterns("/**")
                .excludePathPatterns("/dist/**", "/store/**", "/static/**");
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        String location = "file:///" + siteOptions.getLocation();
        registry.addResourceHandler("/dist/**")
                .addResourceLocations("classpath:/static/dist/");
        registry.addResourceHandler("/theme/*/dist/**")
                .addResourceLocations("classpath:/templates/")
                .addResourceLocations(location + "/storage/templates/");
        registry.addResourceHandler("/storage/avatars/**")
                .addResourceLocations(location + "/storage/avatars/");
        registry.addResourceHandler("/storage/thumbnails/**")
                .addResourceLocations(location + "/storage/thumbnails/");
    }

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(fastJsonHttpMessageConverter);
    }

}

文件上传方法:

public String serverUpload(@RequestParam("file") MultipartFile file, HttpServletRequest req) throws FileNotFoundException {
        // 获取上传文件名
        String filename = file.getOriginalFilename();
        // 将文件存储在运行环境的目录中
        String serverpath = req.getSession().getServletContext().getRealPath("static/");
        File filepath = new File(serverpath, filename);
        // 判断路径是否存在,如果不存在就创建一个
        if (!filepath.getParentFile().exists()) {
            filepath.getParentFile().mkdirs();
        }
        try {
            // 写入文件
            file.transferTo(new File(serverpath + File.separator + filename));
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 返回一个可以直接访问的地址,如http://localhost:8080/static/1.jpg
        String serverFilePath = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + "/static/" + filename;
        return serverFilePath;
    }