1.配置文件
bootstrap.yml
file:
path:
httpResURL: http://122.246.1.148:19086
SAVE_PATH: /data/images
resURI: /wzq/
2.文件工具类
import cn.hutool.core.io.FileUtil;
import com.vinsuan.park.platform.biz.FilePathConfig;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
@Slf4j
@AllArgsConstructor
public class FileUtils {
public static String upload(MultipartFile file, String pkno, String type, String plateNo) {
LocalDateTime localDateTime = LocalDateTime.now();
String yyyyMMdd = localDateTime.format(DateTimeFormatter.ofPattern("yyyyMMdd"));
String HHmmss = localDateTime.format(DateTimeFormatter.ofPattern("HHmmss"));
//文件名绑定后缀 pkno_type_plateNo_20191011_143600(车场-进出-车牌-年月日-时分秒)
String md5File = pkno + "_" + type + "_" + plateNo + "_" + yyyyMMdd + "_" + HHmmss + ".jpg";
File path = new File(FilePathConfig.savePath + FilePathConfig.resUri);
if (!path.exists()) {
path.mkdirs();
}
File localFile = new File(FilePathConfig.savePath + FilePathConfig.resUri, md5File);
if (!FileUtil.exist(localFile)) {
//创建一个新文件
File attachFile = FileUtil.touch(FilePathConfig.savePath + FilePathConfig.resUri, md5File);
//将文件流写入文件中
try {
FileUtil.writeFromStream(file.getInputStream(), attachFile);
} catch (IOException e) {
e.printStackTrace();
}
}
return FilePathConfig.httpResUrl + FilePathConfig.resUri + md5File;
}
/**
* 保存文件(此案例中未使用)
*/
public static File saveFileFromInputStream(InputStream stream, String path, String filename, byte[] buff)
throws IOException {
File file = new File(path);
if (!file.exists()) {
log.info("++++++++++++++创建文件++++++++++++++++++++++++++++:" + path);
file.mkdirs();
}
FileOutputStream fs = new FileOutputStream(path + filename);
byte[] buffer = new byte[1024 * 1024];
int byteread = 0;
if (null == buff || buff.length <= 0) {
while ((byteread = stream.read(buffer)) != -1) {
fs.write(buffer, 0, byteread);
}
} else {
fs.write(buff);
}
fs.flush();
fs.close();
if (null != stream) {
stream.close();
}
return file;
}
// public static void main(String[] args) {
// String imageStr = Base64Utils.GetImageStr("D:\\Pictures\\yy.jpg");
// MultipartFile file = Base64ToMultipartFile.base64ToMultipart(imageStr);
// String upload = FileUtils.upload(file, "cc8888", "1", "浙B88888");
// System.out.println(upload);
// }
}
3.图片转图片BASE64值
4.图片BASE64转MultipartFile
注意:
1.图片存储路径为当前项目盘\data\images\wzq
2.此文件工具栏返回的图片是路径是:http://122.246.1.148:19999/wzq/20191022114711.jpg,不是:http://122.246.1.148:19999/data/images/20191022114711.jpg,是因为访问路径有做映射。wzq->data/images