上传图片,在线地址获取文件大小,md5(32位的)文件转码
程序员文章站
2022-05-01 16:33:55
...
1.上传图片
private void himages(MultipartFile multipartFile){
try {
if (multipartFile.isEmpty()) {
return ResultVo.failure("请选择文件");
}
// 获取文件的名称
String originalFilename = multipartFile.getOriginalFilename();
// 文件后缀 例如:.png
String fileSuffix = originalFilename.substring(originalFilename.lastIndexOf("."));
// uuid 生成文件名
String uuid = String.valueOf(UUID.randomUUID());
// 根路径,在 resources/static/upload
String basePath = ResourceUtils.getURL("classpath:static/ltimages/").getPath();
// 新的文件名,使用uuid生成文件名
String fileName = uuid + fileSuffix;
// 创建新的文件
File fileExist = new File(basePath);
// 文件夹不存在,则新建
System.out.println("是否存在:=="+fileExist.exists());
if (!fileExist.exists()) {
fileExist.mkdirs();
}
// 获取文件对象
File file = new File(basePath, fileName);
// 完成文件的上传
multipartFile.transferTo(file);
System.out.println("文件上传完成!");
// resultVo.setData("http:/127.0.0.1:8070/static/images/"+uuid +fileSuffix);
// http://makers.zcwjvr.com:9010/static/ltimages/bdcf1a7b-3389-4300-a992-9887d9319de9.jpg
System.out.println(uuid +fileSuffix);
return resultVo;
} catch (Exception e) {
e.printStackTrace();
}
return ResultVo.failure("上传失败");
}
2.通过在线地址获取文件大小
/**
* 获取网络文件大小
*/
private long getFileLength(String downloadUrl) throws IOException{
if(downloadUrl == null || "".equals(downloadUrl)){
return 0L ;
}
URL url = new URL(downloadUrl);
HttpURLConnection conn = null;
try {
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("HEAD");
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows 7; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.73 Safari/537.36 YNoteCef/5.8.0.1 (Windows)");
return (long) conn.getContentLength();
} catch (IOException e) {
return 0L;
} finally {
conn.disconnect();
}
}
3.md5(32位的)文件转码
//filename文件根路径
public String getMD5Checksum(String filename) throws Exception {
byte[] b = createChecksum(filename);
String result = "";
for (int i=0; i < b.length; i++) {
result += Integer.toString( ( b[i] & 0xff ) + 0x100, 16).substring(1);//加0x100是因为有的b[i]的十六进制只有1位
}
return result;
}
public byte[] createChecksum(String filename) throws Exception {
InputStream fis = new FileInputStream(filename); //<span style="color: rgb(51, 51, 51); font-family: arial; font-size: 13px; line-height: 20px;">将流类型字符串转换为String类型字符串</span>
byte[] buffer = new byte[1024];
MessageDigest complete = MessageDigest.getInstance("MD5"); //如果想使用SHA-1或SHA-256,则传入SHA-1,SHA-256
int numRead;
do {
numRead = fis.read(buffer); //从文件读到buffer,最多装满buffer
if (numRead > 0) {
complete.update(buffer, 0, numRead); //用读到的字节进行MD5的计算,第二个参数是偏移量
}
} while (numRead != -1);
fis.close();
return complete.digest();
}
上一篇: 2021-01-13
下一篇: 2021-01-17