需要上傳的文件分爲兩種:
- 本地文件上傳:只需要按照OSS中上傳數據的文檔直接編寫即可
- 網上數據上傳:如果上傳的數據來自網絡則需要將其下載到本地,
public String Upload(String word,String path) throws FileNotFoundException {
// 判斷是否有文件
File file=new File(path);
if (word.isEmpty()) {
return null;
}
// 圖片的新名字
String fileName=word+IdWorker.getIdStr()+ file.toString().substring(file.toString().lastIndexOf('.'));
// 服務器保存位置
File newFile=file;
if(FILE_FORMAT.contains(path.substring(path.lastIndexOf('.') + 1).toUpperCase())) {
try {
// 判斷上傳地址是否爲網絡
if (!file.exists()) {
newFile = new File("E:\\" + fileName);
URL url = new URL(path);
DataInputStream dis = new DataInputStream(url.openStream());
OutputStream os = new FileOutputStream(newFile);
byte[] buffer = new byte[1024];
int length;
while ((length = dis.read(buffer)) > 0) {
os.write(buffer, 0, length);
}
os.close();
dis.close();
}
// 判斷上傳圖片是否大於1MB
if (file.length() > 1024 * 1024) {
// 讀取文件
BufferedImage bufImage = ImageIO.read(newFile);
//獲取縮放比例
int wr = (int) (bufImage.getWidth() * 1024 * 1024 / file.length());
int hr = (int) (bufImage.getHeight() * 1024 * 1024 / file.length());
bufImage.getScaledInstance(wr, hr, Image.SCALE_AREA_AVERAGING);
// 把修改過的 bufImage 保存到本地
ImageIO.write(bufImage, "JPG", newFile);
}
} catch (Exception e) {
System.out.println("異常");
}
}
// 將圖片保存到OSS
ObjectMetadata objectMetadata = new ObjectMetadata();
// 生成路徑
String name=words+word+"/"+fileName;
// 創建OSSClient實例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
// 上傳文件流。
InputStream inputStream = new FileInputStream(newFile);
ossClient.putObject(bucketname, app+name, inputStream, objectMetadata);
// 關閉OSSClient。
ossClient.shutdown();
return name;
}
PS:其中word是一個標誌,可有可無,如果刪除需要將代碼中相應的word全部刪除,path是需要上傳文件的路徑。