SpringBoot:上傳單個圖片,上傳圖片壓縮包,讀取本地磁盤圖片

目錄java

1. 上傳單個圖片web

業務方法spring

工具類數據庫

返回結果segmentfault

2. 上傳圖片壓縮包並解壓到指定目錄,和用戶信息匹配服務器

業務方法mvc

工具類app

常量ide

3. 讀取本地磁盤圖片工具

方式1:配置文件

方式2:修改yaml文件

方式3:使用三方工具,如:minio


1. 上傳單個圖片

業務方法

Controller層

@PostMapping("/upload")
    public AjaxResult uploadImg(@RequestParam("file") MultipartFile multipartFile) {
        AjaxResult result = certifInfoService.uploadImg(multipartFile);
        return result;
}

Service層

//    /**
//     * 服務端口
//     */
//    @Value("${server.port}")
//    private String serverPort;
//
//    /**
//     * 在配置文件中配置的文件保存路徑
//     */
//    @Value("${certif.img.storePath}")
//    private String imgStorePath;

    public AjaxResult uploadImg(MultipartFile multipartFile) {

        // 1. 校驗
        if (multipartFile.isEmpty() || StringUtils.isBlank(multipartFile.getOriginalFilename())) {
            return AjaxResult.error("圖片或圖片名缺失");
        }
        String contentType = multipartFile.getContentType();
        if (!contentType.contains("")) {
            return AjaxResult.error("圖片類型缺失");
        }

        // 2. 保存
        String originalFilename = multipartFile.getOriginalFilename();
        log.info("【上傳圖片】:name:{},type:{}", originalFilename, contentType);
        //處理圖片
        //獲取路徑
        String filePath = imgStorePath;
        log.info("【上傳圖片】,圖片保存路徑:{}", filePath);
        try {
            ImageUtil.saveImg(multipartFile, filePath, originalFilename);
        } catch (IOException e) {
            log.info("【上傳圖片】失敗,圖片保存路徑={}", filePath);
            return AjaxResult.error("【上傳圖片】失敗");
        }

        // 3.更新數據庫(上傳圖片名稱和證書編號一致)
        String certifNum = originalFilename.substring(0, originalFilename.lastIndexOf("."));
        CertifInfoDO certifInfoDO = new CertifInfoDO();
        certifInfoDO.setCertifNum(certifNum);
        String imageUrlPath = readUserImageUrl(originalFilename);
        certifInfoDO.setUserImageUrl(imageUrlPath);
        List<CertifInfoDO> certifInfoDOList = Arrays.asList(certifInfoDO);
        certifInfoMapper.batchInsertOrUpdateCertif(certifInfoDOList);
        return AjaxResult.success("【上傳圖片】成功");
    }

工具類

import org.springframework.web.multipart.MultipartFile;

import java.io.*;

public class ImageUtil {

    /**
     * 保存文件,直接以multipartFile形式
     * @param multipartFile
     * @param path 文件保存絕對路徑
     * @param fileName 文件名
     * @return 返回路徑+文件名
     * @throws IOException
     */
    public static String saveImg(MultipartFile multipartFile, String path, String fileName) throws IOException {
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
        FileInputStream fileInputStream = (FileInputStream) multipartFile.getInputStream();
        String fileFullPath = path + File.separator + fileName;
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(fileFullPath));
        byte[] bs = new byte[1024];
        int len;
        while ((len = fileInputStream.read(bs)) != -1) {
            bos.write(bs, 0, len);
        }
        bos.flush();
        bos.close();
        return fileFullPath;
    }
}

返回結果

import java.util.HashMap;
import com.ruoyi.common.core.constant.HttpStatus;
import com.ruoyi.common.core.utils.StringUtils;

/**
 * 操做消息提醒
 * 
 * @author ruoyi
 */
public class AjaxResult extends HashMap<String, Object>
{
    private static final long serialVersionUID = 1L;

    /** 狀態碼 */
    public static final String CODE_TAG = "code";

    /** 返回內容 */
    public static final String MSG_TAG = "msg";

    /** 數據對象 */
    public static final String DATA_TAG = "data";

    /**
     * 初始化一個新建立的 AjaxResult 對象,使其表示一個空消息。
     */
    public AjaxResult()
    {
    }

    /**
     * 初始化一個新建立的 AjaxResult 對象
     * 
     * @param code 狀態碼
     * @param msg 返回內容
     */
    public AjaxResult(int code, String msg)
    {
        super.put(CODE_TAG, code);
        super.put(MSG_TAG, msg);
    }

    /**
     * 初始化一個新建立的 AjaxResult 對象
     * 
     * @param code 狀態碼
     * @param msg 返回內容
     * @param data 數據對象
     */
    public AjaxResult(int code, String msg, Object data)
    {
        super.put(CODE_TAG, code);
        super.put(MSG_TAG, msg);
        if (StringUtils.isNotNull(data))
        {
            super.put(DATA_TAG, data);
        }
    }

    /**
     * 返回成功消息
     * 
     * @return 成功消息
     */
    public static AjaxResult success()
    {
        return AjaxResult.success("操做成功");
    }

    /**
     * 返回成功數據
     * 
     * @return 成功消息
     */
    public static AjaxResult success(Object data)
    {
        return AjaxResult.success("操做成功", data);
    }

    /**
     * 返回成功消息
     * 
     * @param msg 返回內容
     * @return 成功消息
     */
    public static AjaxResult success(String msg)
    {
        return AjaxResult.success(msg, null);
    }

    /**
     * 返回成功消息
     * 
     * @param msg 返回內容
     * @param data 數據對象
     * @return 成功消息
     */
    public static AjaxResult success(String msg, Object data)
    {
        return new AjaxResult(HttpStatus.SUCCESS, msg, data);
    }

    /**
     * 返回錯誤消息
     * 
     * @return
     */
    public static AjaxResult error()
    {
        return AjaxResult.error("操做失敗");
    }

    /**
     * 返回錯誤消息
     * 
     * @param msg 返回內容
     * @return 警告消息
     */
    public static AjaxResult error(String msg)
    {
        return AjaxResult.error(msg, null);
    }

    /**
     * 返回錯誤消息
     * 
     * @param msg 返回內容
     * @param data 數據對象
     * @return 警告消息
     */
    public static AjaxResult error(String msg, Object data)
    {
        return new AjaxResult(HttpStatus.ERROR, msg, data);
    }

    /**
     * 返回錯誤消息
     * 
     * @param code 狀態碼
     * @param msg 返回內容
     * @return 警告消息
     */
    public static AjaxResult error(int code, String msg)
    {
        return new AjaxResult(code, msg, null);
    }
}

2. 上傳圖片壓縮包並解壓到指定目錄,和用戶信息匹配

依賴包

<dependency>
	<groupId>net.lingala.zip4j</groupId>
	<artifactId>zip4j</artifactId>
	<version>1.3.2</version>
</dependency>

業務方法

Controller層

@PostMapping("/zip")
    public AjaxResult uploadImgZip(@RequestParam("file") MultipartFile zipFile) throws IOException {
        AjaxResult result = certifInfoService.uploadImgZip(zipFile);
        return result;
        
    }

Service層

//    /**
//     * 服務端口
//     */
//    @Value("${server.port}")
//    private String serverPort;
//
//    /**
//     * 在配置文件中配置的文件保存路徑
//     */
//    @Value("${certif.img.storePath}")
//    private String imgStorePath;
 /**
     * @Title: 批量證書圖片上傳
     * @MethodName: uploadImgZip
     * @param zipFile
     * @Exception
     * @Description:
     *
     * @author: 王延飛
     */
    @Override
    public AjaxResult uploadImgZip(MultipartFile zipFile) throws IOException {

        // 1. 參數校驗
        if (Objects.isNull(zipFile)) {
            return AjaxResult.error("【批量證書圖片上傳】缺乏zip包");
        }
        String fileContentType = zipFile.getContentType();

        if (!Constants.CONTENT_TYPE_ZIP.equals(fileContentType)
                && !Constants.CONTENT_TYPE_ZIP_COMPRESSED.equals(fileContentType)
        ) {
            return AjaxResult.error("【批量證書圖片上傳】類型不是zip");
        }

        // 2. 保存
        //將壓縮包保存在指定路徑
        String filePath = imgStorePath + File.separator + zipFile.getName();
        //保存到服務器
        boolean saveFile = FileUtils.saveFile(zipFile, filePath);
        if (!saveFile) {
            return AjaxResult.error("【批量證書圖片上傳】失敗");
        }

        // 3. 更新數據庫
        InputStream in = new BufferedInputStream(new FileInputStream(filePath));
        ZipInputStream zin = new ZipInputStream(in);
        ZipEntry ze;
        ArrayList<CertifInfoDO> certifInfoDOS = new ArrayList<>();
        while ((ze = zin.getNextEntry()) != null) {
            if (ze.isDirectory()) {
            } else {
                String originalFilename = ze.getName();
                if (StringUtils.isBlank(originalFilename)) {
                    return AjaxResult.error("【批量證書圖片上傳】存在文件名缺失");
                }
                String certifNum = originalFilename.substring(0, originalFilename.lastIndexOf("."));
                CertifInfoDO certifInfoDO = new CertifInfoDO();
                certifInfoDO.setCertifNum(certifNum);
                String imageUrlPath = readUserImageUrl(originalFilename);
                certifInfoDO.setUserImageUrl(imageUrlPath);
                certifInfoDOS.add(certifInfoDO);

            }
        }
        zin.closeEntry();
        certifInfoMapper.batchInsertOrUpdateCertif(certifInfoDOS);

        String destPath = imgStorePath + File.separator;
        // 4. 解壓,並刪除zip包
        boolean unPackZip = FileUtils.unPackZip(new File(filePath), "", destPath, true);
        if (unPackZip) {
            return AjaxResult.success("【批量證書圖片上傳解壓】成功");
        } else {
            return AjaxResult.error("【批量證書圖片上傳解壓】失敗");
        }


    }

    /**
     * @Title: 圖片路徑
     * @MethodName: getUserImageUrl
     * @param originalFilename
     * @Return java.lang.String
     * @Exception
     * @Description:
     *
     * @author: 王延飛
     */
    private String readUserImageUrl(String originalFilename) {
        // http://localhost:8989/image/11
        StringBuilder imageUrl = new StringBuilder("http://");
        String hostAddress = null;
        try {
            hostAddress = Inet4Address.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            log.info("【圖片路徑】獲取失敗:{}", e);
            return null;
        }
        String imageUrlPath = imageUrl.append(hostAddress)
                .append(":").append(serverPort)
                .append("/image/").append(originalFilename)
                .toString().trim();
        return imageUrlPath;
    }

工具類

import com.ruoyi.common.core.constant.Constants;
import net.lingala.zip4j.core.ZipFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

/**
 * @Title: zip文件解壓
 * @Description:
 *
 * @author: 王延飛
 * @date: 2020/8/14 0014 10:25
 * @version V1.0
 */
public class FileUtils {

    protected static Logger log = LoggerFactory.getLogger(FileUtils.class);

    /**
     * @Title: 文件保存
     * @MethodName: saveFile
     * @param file
     * @param path
     * @Return boolean
     * @Exception
     * @Description:
     *
     * @author: 王延飛
     * @date: 2020/8/14 0014 11:04
     */
    public static boolean saveFile(MultipartFile file, String path) {

        File desFile = new File(path);
        if (!desFile.getParentFile().exists()) {
            desFile.mkdirs();
        }
        try {
            file.transferTo(desFile);
        } catch (IOException e) {
            log.error("【文件保存】異常,路徑:{} ,異常信息:{} ", path, e);
            return false;
        }
        return true;
    }

    /**
     * @Title: 獲取項目classpath路徑
     * @MethodName: getApplicationPath
     * @param
     * @Return java.lang.String
     * @Exception
     * @Description:
     *
     * @author: 王延飛
     */
    public static String getApplicationPath() {

        //獲取classpath
        ApplicationHome h = new ApplicationHome(CertifApplication.class);
        File jarF = h.getSource();
        return jarF.getParentFile() + File.separator;
    }

    /**
     * zip文件解壓
     *
     * @param destPath 解壓文件路徑
     * @param zipFile  壓縮文件
     * @param password 解壓密碼(若是有)
     * @param isDel 解壓後刪除
     */
    public static boolean unPackZip(File zipFile, String password, String destPath, boolean isDel) {
        try {
            ZipFile zip = new ZipFile(zipFile);
            /*zip4j默認用GBK編碼去解壓*/
            zip.setFileNameCharset(Constants.UTF8);
            log.info("【文件解壓】begin unpack zip file....");
            zip.extractAll(destPath);
            // 若是解壓須要密碼
            if (zip.isEncrypted()) {
                zip.setPassword(password);
            }
        } catch (Exception e) {
            log.error("【文件解壓】異常,路徑:{} ,異常信息:{} ", destPath, e);
            return false;
        }

        if (isDel) {
            zipFile.deleteOnExit();
        }
        return true;
    }


    /**
     * @Title: 讀取文件內容
     * @MethodName:  readZipFile
     * @param file
     * @Return void
     * @Exception
     * @Description:
     *
     * @author: 王延飛
     * @date:  2020/8/14 0014 20:26
     */
    public static void readZipFile(String file) throws Exception {
        
        java.util.zip.ZipFile zf = new java.util.zip.ZipFile(file);
        InputStream in = new BufferedInputStream(new FileInputStream(file));
        ZipInputStream zin = new ZipInputStream(in);
        ZipEntry ze;
        while ((ze = zin.getNextEntry()) != null) {
            if (ze.isDirectory()) {
            } else {
                System.err.println("file - " + ze.getName());

            }
        }
        zin.closeEntry();
    }
}

常量

/**
 * 通用常量信息
 * 
 */
public class Constants
{
    /**
     * UTF-8 字符集
     */
    public static final String UTF8 = "UTF-8";

    /**
     * GBK 字符集
     */
    public static final String GBK = "GBK";

    /**
     * http請求
     */
    public static final String HTTP = "http://";

    /**
     * https請求
     */
    public static final String HTTPS = "https://";

    /**
     * 文件類型 <application/zip>
     */
    public static final String CONTENT_TYPE_ZIP = "application/zip";

    /**
     * 文件類型 <application/x-zip-compressed>
     */
    public static final String CONTENT_TYPE_ZIP_COMPRESSED = "application/x-zip-compressed";
}

3. 讀取本地磁盤圖片

按照以下方式修改後,就能夠經過如下路徑訪問

http://localhost:8989/image/11.png

方式1:配置文件

package com.ruoyi.certif.config;

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;
/**
 * @Title:  訪問本地(磁盤)圖片
 * @ClassName: com.ruoyi.certif.config.SourceConfiguration.java
 * @Description:
 *
 * @author: 王延飛
 * @date:  2020/8/14 0014 15:26
 * @version V1.0
 */
@Configuration
public class SourceConfiguration extends WebMvcConfigurerAdapter {

    /**
     * 在配置文件中配置的文件保存路徑
     */
    @Value("${certif.img.storePath}")
    private String imgStorePath;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {

        //其中/cetif/photo表示訪問的前綴。"file:imgStorePath"是文件真實的存儲路徑(如:)
        // 訪問路徑以下:http://localhost:8088/cetif/photo/XXX.png
        registry.addResourceHandler("/cetif/photos/**").addResourceLocations("file:"+imgStorePath);
        super.addResourceHandlers(registry);
    }

}

方式2:修改yaml文件

# Tomcat
server:
  port: 8989

# 圖片存放路徑
certif:
  img:
    storePath: D:\home\fly

# Spring
spring:
  # 訪問圖片路徑爲/image/**
  mvc:
    static-path-pattern: /image/**
  # 圖片本地存放路徑
  resources:
    static-locations: file:${certif.img.storePath}
  application:
    # 應用名稱
    name: ruoyi-certif
  profiles:
    # 環境配置
    active: dev

方式3:使用三方工具,如:minio

 

參考鏈接:http://www.noobyard.com/article/p-hdwzesea-dw.html