Java 上传文件/上传图片 data:image/jpg, data:image/jpeg, data:image/png 亲测

  • 上传通过 base64 编码后的图 Data URL

1. 判断允许上传文件的 文件后缀/图片后缀/相片后缀 和 其它工具类


import org.springframework.stereotype.Component;
import java.io.File;
import java.util.Arrays;
import java.util.List;

@Component
public class FileUtil {
    public static final List<String> IMAGE_EXTENSIONS = Arrays.asList(".jpg", ".jpeg", ".png");
}

import java.util.UUID;

public class CommonUtil {
    public static String getUUID() {
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        return uuid;
    }
}

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class DateUtil {
    public static final String HH = "HH";
    public static final String YYYY_MM_DD = "yyyy-MM-dd";
    public static final DateTimeFormatter FORMATTER_HH = DateTimeFormatter.ofPattern(HH);
    public static final DateTimeFormatter FORMATTER_YYYY_MM_DD = DateTimeFormatter.ofPattern(YYYY_MM_DD);
    public static String getHH() {
        return FORMATTER_HH.format(LocalDateTime.now());
    }
    public static String getYYYYMMDD() {
        return FORMATTER_YYYY_MM_DD.format(LocalDateTime.now());
    }
}

2. 上传接口


    @PostMapping("/updateImageOfWeb.do")
    public Map<String, String> updateImageOfWeb(@RequestParam("image") String fileTemp) {
        	Map<String, String> result = new HashMap<>();
        if (StringUtils.isBlank(fileTemp)) {
			result.put("message", "请选择图片!");
			return result;
        }

        String suffix = null;
        if (fileTemp.startsWith("data:image/jpg")) {
            suffix = ".jpg";
        } else if (fileTemp.startsWith("data:image/jpeg")) {
            suffix = ".jpeg";
        } else if (fileTemp.startsWith("data:image/png")) {
            suffix = ".png";
        }

        if (suffix == null) {
			result.put("message", "图片格式错误!");
			return result;
        }

        if (!FileUtil.IMAGE_EXTENSIONS.contains(suffix)) {
			result.put("message", "图片格式错误!");
			return result;
        }

        String lastFilePath;
        String newFileName = CommonUtil.getUUID() + suffix;
        String folderName = File.separator + "temp" + File.separator;
        String relativePath = folderName + DateUtil.getYYYYMMDD() + File.separator + DateUtil.getHH();
        String filePath = "D:\\file" + relativePath;
        String fileUrl = null;
        File targetFile = new File(filePath);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }

        FileOutputStream out = null;
        final BASE64Decoder decoder = new BASE64Decoder();
        try {
            lastFilePath = filePath + File.separator + newFileName;
            out = new FileOutputStream(lastFilePath);
            byte[] decoderBytes = decoder.decodeBuffer(fileTemp.split(",")[1]);
            out.write(decoderBytes);
            fileUrl = "http://127.0.0.1:9000" + relativePath + File.separator + newFileName;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        if (fileUrl == null) {
			result.put("message", "图片上传失败!");
			return result;
        }

		result.put("message", "上传成功!");
		result.put("url", fileUrl);
		return result;
    }

3. 上传成功


url => http://127.0.0.1:9000/temp/2019-09-12/14/0eac00b96f134652b34172e84febe8d1.jpg

如果您觉得有帮助,欢迎点赞哦 ~ 谢谢!!

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 创作都市 设计师:CSDN官方博客 返回首页