有時候在java網站開發過程中,經常要用到下載遠程文件到本地,如下載OSS的文件或者圖片到本地服務器,然后再用郵件發送。實現代碼大概如下:
package com.fwwl.fwqy.common.utils;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
public class downloadUtils {
/**
* 下載遠程文件并保存到本地
*
* @param remoteFilePath-遠程文件路徑
* @param localFilePath-本地文件路徑(帶文件名)
*/
public static void downloadFile1(String remoteFilePath, String localFilePath) {
URL urlfile = null;
HttpURLConnection httpUrl = null;
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
File f = new File(localFilePath);
try {
urlfile = new URL(remoteFilePath);
httpUrl = (HttpURLConnection) urlfile.openConnection();
httpUrl.connect();
bis = new BufferedInputStream(httpUrl.getInputStream());
bos = new BufferedOutputStream(new FileOutputStream(f));
int len = 2048;
byte[] b = new byte[len];
while ((len = bis.read(b)) != -1) {
bos.write(b, 0, len);
}
bos.flush();
bis.close();
httpUrl.disconnect();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
bis.close();
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 下載遠程文件并保存到本地
*
* @param remoteFilePath-遠程文件路徑
* @param localFilePath-本地文件路徑(帶文件名)
*/
public static void downloadFile2(String remoteFilePath, String localFilePath) {
URL website = null;
ReadableByteChannel rbc = null;
FileOutputStream fos = null;
try {
website = new URL(remoteFilePath);
rbc = Channels.newChannel(website.openStream());
fos = new FileOutputStream(localFilePath);//本地要存儲的文件地址 例如:test.txt
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
} catch (Exception e) {
e.printStackTrace();
}finally{
if(fos!=null){
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(rbc!=null){
try {
rbc.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
但這里會有個安全問題,比如別人把遠程的文件改為木馬,那么下載到服務器就容易對網站進行破壞,所以在下載的過程中,最好使用內部存儲的文件,路徑不要被篡改,然后對文件的類型進行判斷,同時不要給文件執行權限。
如沒特殊注明,文章均為方維網絡原創,轉載請注明來自http://www.sdlwjx666.com/news/8575.html