计算URL文件大小代码
详解:
1.首先我们拿到前端上传文件传来的文件url地址
2.然后对url地址进行截取拆分
3.然后对文件名进行utf-8编码(进行UTF-8编码是为了解决中文文件名计算不出来的情况)
4.然后再拼接起来进行计算
public AjaxResult add(@RequestBody Documents documents){
// 解析filePath
String filePath = documents.getFilePath();
try {
//根据 / 截取
int lastSlashIndex = filePath.lastIndexOf("/");
//截取文件名和文件名之前的路径
String filePrefix = filePath.substring(0, lastSlashIndex + 1); // 包含最后一个斜线
String fileName = filePath.substring(lastSlashIndex + 1);
//然后再拼接,进行UTF-8编码
String finalURL = filePrefix + URLEncoder.encode(fileName, "UTF-8");
URL url = new URL(finalURL);
// 发送HTTP请求并接收响应
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// GET请求
conn.setRequestMethod("GET");
// 客户端希望接收的响应内容的压缩方式为无压缩,即希望接收的内容与发送的内容一致。
conn.setRequestProperty("Accept-Encoding", "identity");
long fileSize = conn.getContentLengthLong();
//拼接对应的KB MB
String formattedSize = FileSizeUtil.formatFileSize(fileSize);
documents.setFileSize(formattedSize);
} catch (IOException e) {
e.printStackTrace();
}
拼接指定大小后缀 formatFileSize方法
/**
* 根据大小拼接 "B", "KB", "MB", "GB"
* @param fileSize
* @return
*/
public static String formatFileSize(long fileSize) {
if (fileSize <= 0) {
return "0B";
}
final String[] units = new String[]{"B", "KB", "MB", "GB"};
int digitGroups = (int) (Math.log10(fileSize) / Math.log10(1024));
return String.format("%.2f %s", fileSize / Math.pow(1024, digitGroups), units[digitGroups]);
}
如果有更好的办法,欢迎评论区留言讨论.