android上傳檔案至伺服器(android端+伺服器端)
引言:本來android檔案上傳的部落格在網上挺多的,不過好些都只是有前臺android端的上傳,並沒有後臺伺服器端的接收。而且自己寫的時候也確實遇見了一些之前沒注意到的地方,寫出來也算是給自己提個醒。
我這裡就不把全部的程式碼都貼出來了,就只貼一下核心程式碼就算了,如果有什麼疑問或者不對的地方,歡迎指教。
我要做的是把我app的日誌檔案上傳到指定伺服器的功能。並沒有寫的太複雜,我參考鴻洋大神的部落格的時候,看他對DataOutputStream寫入了headinfo和endinfo,但是我沒理解這樣寫的目的,所以也沒加,如果有知道的可以告訴我呦。
廢話不多說,直接上程式碼。
下面是android端上傳檔案程式碼:
/**
* 上傳檔案到伺服器
* @param context
* @param uploadUrl 上傳伺服器地址
* @param oldFilePath 本地檔案路徑
*/
public static void uploadLogFile(Context context, String uploadUrl, String oldFilePath){
try {
URL url = new URL(path);
HttpURLConnection con = (HttpURLConnection)url.openConnection();
// 允許Input、Output,不使用Cache
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false);
con.setConnectTimeout(50000);
con.setReadTimeout(50000);
// 設定傳送的method=POST
con.setRequestMethod("POST");
//在一次TCP連線中可以持續傳送多份資料而不會斷開連線
con.setRequestProperty("Connection" , "Keep-Alive");
//設定編碼
con.setRequestProperty("Charset", "UTF-8");
//text/plain能上傳純文字檔案的編碼格式
con.setRequestProperty("Content-Type", "text/plain");
// 設定DataOutputStream
DataOutputStream ds = new DataOutputStream(con.getOutputStream());
// 取得檔案的FileInputStream
FileInputStream fStream = new FileInputStream(oldFilePath);
// 設定每次寫入1024bytes
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int length = -1;
// 從檔案讀取資料至緩衝區
while ((length = fStream.read(buffer)) != -1) {
// 將資料寫入DataOutputStream中
ds.write(buffer, 0, length);
}
ds.flush();
fStream.close();
ds.close();
if(con.getResponseCode() == 200){
logger.info("檔案上傳成功!上傳檔案為:" + oldFilePath);
}
} catch (Exception e) {
e.printStackTrace();
logger.info("檔案上傳失敗!上傳檔案為:" + oldFilePath);
logger.error("報錯資訊toString:" + e.toString());
}
}
伺服器這裡我是用我自己本地的tomcat做的測試伺服器,這個你們可以通過配置檔案或者自己指定伺服器。
下面是伺服器端接收檔案程式碼:
@RequestMapping(value = "/uploadFile")
public void uploadFile(HttpServletRequest request, HttpServletResponse response)
throws IOException
{
InputStream is = request.getInputStream();
DataInputStream dis = new DataInputStream(is);
String result = "";
try {
result = saveFile(dis);
} catch (Exception e) {
e.printStackTrace();
result = "uploaderror";
}
request.getSession().invalidate();
response.setContentType("text/html;charset=UTF-8");
ObjectOutputStream dos = new ObjectOutputStream(
response.getOutputStream());
dos.writeObject(result);
dos.flush();
dos.close();
dis.close();
is.close();
}
/**
* 儲存檔案
* @param dis
* @return
*/
private String saveFile(DataInputStream dis) {
String fileurl = "F:/apache-tomcat-7.0.70/webapps/upload/2017-06-12.log";
File file = new File(fileurl);
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
FileOutputStream fps = null;
try {
fps = new FileOutputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int length = -1;
try {
while ((length = dis.read(buffer)) != -1) {
fps.write(buffer, 0, length);
}
} catch (IOException e) {
e.printStackTrace();
}
try {
fps.flush();
fps.close();
} catch (IOException e) {
e.printStackTrace();
}
return "success";
}
個人情況總結:我個人出現的情況是,上傳的檔案沒有資料,就是DataOutputStream在伺服器端接收的時候,是沒內容的,可是我在android端除錯的時候,明明是能看到資料,後來找了1天時間,找到了原因。因為我上傳的是日誌檔案,屬於純文字檔案,可是最開始我設定http中Content-Type格式的時候,我設定的是multipart/form-data格式,到後面改成text/plain格式才能正常上傳(之前的我是在網上直接扒下來的,坑~)。所以這裡的格式要根據你實際的檔案型別來設定。
這裡關於Content-Type格式的問題,我參考了以下部落格,更詳細的講解可過去看看:
http://blog.csdn.net/blueheart20/article/details/45174399
常見的媒體格式型別如下:
text/html : HTML格式
text/plain :純文字格式
text/xml : XML格式
image/gif :gif圖片格式
image/jpeg :jpg圖片格式
image/png:png圖片格式
以application開頭的媒體格式型別:
application/xhtml+xml :XHTML格式
application/xml : XML資料格式
application/atom+xml :Atom XML聚合格式
application/json : JSON資料格式
application/pdf :pdf格式
application/msword : Word文件格式
application/octet-stream : 二進位制流資料(如常見的檔案下載)
application/x-www-form-urlencoded : <form encType=””>中預設的encType,form表單資料被編碼為key/value格式傳送到伺服器(表單預設的提交資料的格式)
另外一種常見的媒體格式是上傳檔案之時使用的:
multipart/form-data : 需要在表單中進行檔案上傳時,就需要使用該格式
以上就是我們在日常的開發中,經常會用到的若干content-type的內容格式。