標籤:output ati 串連 下載 out write exce app default
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;
}
}
伺服器端實現檔案的上傳和下載