SpringBoot图片上传功能

主要代码部分

返回的是是相对路径的图片连接

package com.zkc.student.controller;

import com.zkc.student.utils.DigestUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.Date;

/**
 * 主要用于图片上传(如果可以看懂,稍加修改就可以文件上传)
 */
@Controller
public class ImgUplod {

    public static final String IMAGE_PNG = "image/png";

    public static final String IMAGE_JPG = "image/jpg";

    public static final String IMAGE_JPEG = "image/jpeg";

    public static final String IMAGE_BMP = "image/bmp";

    public static final String IMAGE_GIF = "image/gif";

    /**
     * 默认的文件名最大长度 100
     */
    public static final int DEFAULT_FILE_NAME_LENGTH = 100;

    /**
     * 默认大小 50M
     */
    public static final long DEFAULT_MAX_SIZE = 50 * 1024 * 1024;

    /**
     *
     * 允许上传的图片格式
     *
     * */
    public static final String[] DEFAULT_ALLOWED_EXTENSION = {
            // 图片
            "bmp", "gif", "jpg", "jpeg", "png",
            // word excel powerpoint
            "doc", "docx", "xls", "xlsx", "ppt", "pptx", "html", "htm", "txt",
            // 压缩文件
            "rar", "zip", "gz", "bz2",
            // pdf
            "pdf"};

    public static final String[] IMAGE_EXTENSION = {"bmp", "gif", "jpg", "jpeg", "png"};

    public static final String[] FLASH_EXTENSION = {"swf", "flv"};

    public static final String[] MEDIA_EXTENSION = {"swf", "flv", "mp3", "wav", "wma", "wmv", "mid", "avi", "mpg", "asf", "rm", "rmvb"};

    private static int counter = 0;

    @PostMapping("/uplod")
    @ResponseBody
    public String Uplod(@RequestParam("imgFile") MultipartFile imgFile) throws IOException {
        if (imgFile.isEmpty()) { //判断是否为空
            return "请上传图片!";
        }

        File fileDir = new File("/student");
        if (!fileDir.isDirectory()) {   //如果没有 student  文件就创建
            fileDir.mkdirs();   //创建 student 文件
        }

        int ImgFileNamelength = imgFile.getOriginalFilename().length();  //获取名字的长度
        if (ImgFileNamelength > DEFAULT_FILE_NAME_LENGTH) { //判断图片名字是否超过100
            return "图片名字长度超过100";
        }

        long ImgFileSize = imgFile.getSize();  //获取当前图片大小(字节)
        if (DEFAULT_MAX_SIZE != -1 && ImgFileSize > DEFAULT_MAX_SIZE) {  //&& 两个条件都成立才行
            return "图片大小超过50M";
        }

        String extension = FilenameUtils.getExtension(imgFile.getOriginalFilename()); //获取文件名的后缀
        if (StringUtils.isEmpty(extension)) { //判断是否为空 如果为空执行一下操作
            extension =  Extension(imgFile.getContentType());
        }

        String ImgFileName = imgFile.getOriginalFilename();  // 获取图片名字
        if (DEFAULT_ALLOWED_EXTENSION != null && !isAllowedExtension(extension, DEFAULT_ALLOWED_EXTENSION)) { //判断MIME类型是否是允许的MIME类型 (通俗的解释就是判断当前上传的文件格式是不是允许上传的格式)
            if (DEFAULT_ALLOWED_EXTENSION == IMAGE_EXTENSION) {
                return DEFAULT_ALLOWED_EXTENSION + "--------" + extension + "--------" + ImgFileName;
            } else if (DEFAULT_ALLOWED_EXTENSION == FLASH_EXTENSION) {
                return DEFAULT_ALLOWED_EXTENSION + "--------" + extension + "--------" + ImgFileName;
            } else if (DEFAULT_ALLOWED_EXTENSION == MEDIA_EXTENSION) {
                return DEFAULT_ALLOWED_EXTENSION + "--------" + extension + "--------" + ImgFileName;
            } else {
                return DEFAULT_ALLOWED_EXTENSION + "--------" + extension + "--------" + ImgFileName;
            }
        }

        String fileName = "/" + DateFormatUtils.format(new Date(), "yyyy/MM/dd") + "/" + encodingFilename(ImgFileName) + "." + extension; //        /年/月/日/(加密图片名字).(原图片的后缀名)
        File desc = new File(fileDir.getAbsolutePath() + File.separator + fileName);
        if (!desc.getParentFile().exists()) {
            desc.getParentFile().mkdirs();
        }
        if (!desc.exists()) {
            desc.createNewFile();
        }

        imgFile.transferTo(desc);

        String pathFileName = fileDir + fileName;

        if (StringUtils.contains(fileDir.getAbsolutePath(), ":")) {
            pathFileName = StringUtils.substringAfterLast(fileDir.getAbsolutePath(), ":") + fileName; // windows 去除盘符
        }

        pathFileName = pathFileName.replaceAll("\\\\", "/");  //将 反斜杠("\")变成  正斜杠 ("/")

        return pathFileName;
    }


    /**
     * 判断MIME类型是否是允许的MIME类型
     *
     * @param extension
     * @param allowedExtension
     * @return
     */
    public static final boolean isAllowedExtension(String extension, String[] allowedExtension) {
        for (String str : allowedExtension) {
            if (str.equalsIgnoreCase(extension)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 编码文件名
     */
    private static final String encodingFilename(String filename) {
        filename = filename.replace("_", " ");
        filename = DigestUtil.hmacSign(filename + System.nanoTime() + counter++);
        return filename;
    }

    /**
     *
     * */
    public static String Extension(String prefix) {
        switch (prefix) {
            case IMAGE_PNG:
                return "png";
            case IMAGE_JPG:
                return "jpg";
            case IMAGE_JPEG:
                return "jpeg";
            case IMAGE_BMP:
                return "bmp";
            case IMAGE_GIF:
                return "gif";
            default:
                return "";
        }
    }


}

图片上床图片路径映射
package com.zkc.student.config;


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 WebMvcConfiguration implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/student/**").addResourceLocations("file:/student/");
    }
}

对图片名字重命名(用了md5加密的方式)
package com.zkc.student.utils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Random;

public class DigestUtil {

    private static String encodingCharset = "UTF-8";

    public static String hmacSign(String aValue, int length) {

        String md5Str = hmacSign(aValue);
        if (md5Str.length() < length) {
            length = md5Str.length();
        }
        return md5Str.substring(0, length);
    }

    public static String hmacSign(String aValue) {
        return hmacSign(aValue, "zkc");
    }

    /**
     * @param aValue
     * @param aKey
     * @return
     */
    public static String hmacSign(String aValue, String aKey) {
        byte k_ipad[] = new byte[64];
        byte k_opad[] = new byte[64];
        byte keyb[];
        byte value[];
        try {
            keyb = aKey.getBytes(encodingCharset);
            value = aValue.getBytes(encodingCharset);
        } catch (UnsupportedEncodingException e) {
            keyb = aKey.getBytes();
            value = aValue.getBytes();
        }

        Arrays.fill(k_ipad, keyb.length, 64, (byte) 54);
        Arrays.fill(k_opad, keyb.length, 64, (byte) 92);
        for (int i = 0; i < keyb.length; i++) {
            k_ipad[i] = (byte) (keyb[i] ^ 0x36);
            k_opad[i] = (byte) (keyb[i] ^ 0x5c);
        }

        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {

            return null;
        }
        md.update(k_ipad);
        md.update(value);
        byte dg[] = md.digest();
        md.reset();
        md.update(k_opad);
        md.update(dg, 0, 16);
        dg = md.digest();
        return toHex(dg);
    }

    public static int randomCode() {
        //0550
        //550
        //0 - 8999
        //0+1000  1000
        //8999   1000  9999
        return new Random().nextInt(9000) + 1000;
    }

    public static String toHex(byte input[]) {
        if (input == null)
            return null;
        StringBuffer output = new StringBuffer(input.length * 2);
        for (int i = 0; i < input.length; i++) {
            int current = input[i] & 0xff;
            if (current < 16)
                output.append("0");
            output.append(Integer.toString(current, 16));
        }

        return output.toString();
    }

    /**
     * @param args
     * @param key
     * @return
     */
    public static String getHmac(String[] args, String key) {
        if (args == null || args.length == 0) {
            return (null);
        }
        StringBuffer str = new StringBuffer();
        for (int i = 0; i < args.length; i++) {
            str.append(args[i]);
        }
        return (hmacSign(str.toString(), key));
    }

    /**
     * @param aValue
     * @return
     */
    public static String digest(String aValue) {
        aValue = aValue.trim();
        byte value[];
        try {
            value = aValue.getBytes(encodingCharset);
        } catch (UnsupportedEncodingException e) {
            value = aValue.getBytes();
        }
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance("SHA1");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
        return toHex(md.digest(value));


    }
}

pom.xml
        
        <!--工具类-->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.7</version>
        </dependency>

        <!-- io常用工具类 -->
        <!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.6</version>
        </dependency>

这里只是针对图片上传写的,稍加修改就可以上传其他文件

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值