有时候在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.cdpcwl.com/news/8575.html