import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
/**
* 文件上传和下载
* @author 20170323
*
*/
public class FileNetUploadAndDownload {
/**
* 文件上传
* @param String 文件上传路径
* @param String 文件本地路径
* @return
* @throws Exception
*/
public String fileUpload(String urlPath,String fileLocation) throws Exception{
String res = "";
//建立连接客户端
HttpClient httpclient = new DefaultHttpClient();
//连接服务器
HttpPost httppost = new HttpPost(urlPath);
//加载文件
FileBody file = new FileBody(new File(fileLocation));
//初始化加载器?
MultipartEntity reqEntity = new MultipartEntity();
//加载文件
reqEntity.addPart("file", file);
//加载加载器
httppost.setEntity(reqEntity);
//准备发送数据(??)
HttpResponse response = httpclient.execute(httppost);
//准备发送数据(??)
HttpEntity httpEntity = response.getEntity();
//生成流
BufferedReader br = new BufferedReader(new InputStreamReader(httpEntity.getContent(), "UTF-8"));
StringBuffer backData = new StringBuffer();
String line = null;
//发送
while ((line = br.readLine()) != null) {
backData.append(line);
}
res = backData.toString();
System.out.println(res);
return res;
}
/**
* 文件下载
* @param String 下载路径
* @param String 文件名
* @param String 本地存储路径
* @return
* @throws Exception
*/
public String fileDownload(String fileNetPath,String FileName,String UpFilePath) throws Exception{
//连接服务器
URL url = new URL(fileNetPath);
//生成流
InputStream is = url.openStream();
//生成本地文件
UpFilePath +="/"+FileName;
File outFlie = new File(UpFilePath);
if(!outFlie.getParentFile().exists()){
outFlie.getParentFile().mkdir();
}
if(!outFlie.exists()){
outFlie.createNewFile();
}
OutputStream output = new FileOutputStream(outFlie);
int temp = 0;
//写入文件
while((temp = is.read()) != -1){
output.write(temp);
}
is.close();
output.close();
System.out.println(is);
return UpFilePath;
}
}