MultipartFile 实现图片上传

文件上传实现

@PostMapping("/admin/upload/file")
    public ApiRestResponse upload(HttpServletRequest httpServletRequest,
            @RequestParam("file") MultipartFile file) {
        String fileName = file.getOriginalFilename();
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        //生成文件名称UUID
        UUID uuid = UUID.randomUUID();
        String newFileName = uuid.toString() + suffixName;
        //1.创建文件目录
        File fileDirectory = new File(Constant.FILE_UPLOAD_DIR);
        //2.创建目标文件
        File destFile = new File(Constant.FILE_UPLOAD_DIR + newFileName);
        //3.判断文件目录是否存在,不存在则创建
        if (!fileDirectory.exists()) {
            if (!fileDirectory.mkdir()) {
                throw new ImoocMallException(ImoocMallExceptionEnum.MKDIR_FAILED);
            }
        }
        try {
        //4.上传图片
            file.transferTo(destFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            //返回图片的网络地址(要想直接在网络上进行该图片的访问,要将图片的网络地址与本地地址映射起来)
            return ApiRestResponse.success(getHost(new URI(httpServletRequest.getRequestURL() + "")) + "/images/"+ newFileName);
        } catch (URISyntaxException e) {
            return ApiRestResponse.error(ImoocMallExceptionEnum.UPLOAD_FAILED);
        }
    }

    private URI getHost(URI uri) {
        URI effectiveURI;
        try {
            effectiveURI = new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(),
                    null, null, null);
        } catch (URISyntaxException e) {
            effectiveURI = null;
        }
        return effectiveURI;
    }

MultipartFile 通过 MultipartFile .transferTo( destFile), 仅需要这步骤,就可以把图片文件存到服务器所在的电脑的任意一个盘或者路径里面,在之前要先判断图片文件的保存目录路径是否存在,如果不存在则要先创建。否则你也许会报一个错误,“java.io.FileNotFoundException 拒绝访问

将网络地址与本地资源进行映射

package com.imooc.mall.config;

import com.imooc.mall.common.Constant;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * 描述:     配置地址映射
 */ 
@Configuration
public class ImoocMallWebMvcConfig implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {        
        registry.addResourceHandler("/images/**")
                .addResourceLocations("file:" + Constant.FILE_UPLOAD_DIR);        
    }
}

参考文献

https://blog.csdn.net/qq_41694349/article/details/79855853

posted @ 2021-05-26 15:40  little_mao  阅读(526)  评论(0编辑  收藏  举报