2020-12-13SpingBoot 图片上传工具类使用

工具类:

(直接复制就可以)

package com.guomo.utils;

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 图片上传工具类
 */
public class ImageUploadUtil {

    public static String uploadFile(@RequestParam("file") MultipartFile file, String strPath) throws IOException {
        String fileName = file.getOriginalFilename();//获取文件名
        fileName = getFileName(fileName);
        String filepath = getUploadPath(strPath);
        if (!file.isEmpty()) {
            try (BufferedOutputStream out = new BufferedOutputStream(
                    new FileOutputStream(new File(filepath + File.separator + fileName)))) {
                out.write(file.getBytes());
                out.flush();
                return "/"+strPath+"/"+fileName;
            } catch (FileNotFoundException e) {
                return "error";//( "上传文件失败 FileNotFoundException:" + e.getMessage());
            } catch (IOException e) {
                return "error";//( "上传文件失败 IOException:" + e.getMessage());
            }
        } else {
            return "error";//( "上传文件失败,文件为空");
        }
    }

    /**
     * 文件名后缀前添加一个时间戳
     */
    private static String getFileName(String fileName) {
        int index = fileName.lastIndexOf(".");
        final SimpleDateFormat sDateFormate = new SimpleDateFormat("yyyymmddHHmmss");  //设置时间格式
        String nowTimeStr = sDateFormate.format(new Date()); // 当前时间
        fileName = fileName.substring(0, index) + "_" + nowTimeStr + fileName.substring(index);
        return fileName;
    }

    /**
     * 获取当前系统路径
     */
    private static String getUploadPath(String strPath) throws IOException {

        File file = new File(strPath);
        File fileParent = file.getParentFile();
        if (!fileParent.exists()) {
            fileParent.mkdirs();
        }
        if (!file.exists()) file.mkdirs();

        return file.getAbsolutePath();

    }
}

工具类的使用:

在这里插入图片描述
url为获取工具类返回的路径+文件名,路径为相对路径,如果想要获取绝对路径的话,请修改工具类return。

打开保存的图片:

在localhost,或IP地址 打开

需要在配置静态资源里面写配置,写的有点乱。

在这里插入图片描述
配置完成以后就可以去浏览器访问了。
在这里插入图片描述
这里做个学习记录

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值