因為工作需要,暫時沒有對GPS(2)完成,今天開始完成了,一個檔案上傳的內容的實現,Android要實現檔案上傳,可以利用Socket上傳,也可以類比Web進行上傳,但是如果是使用第一種方式上傳,嚴格的話就得使用TCP,這樣容易產生系統死掉,或者是長時間等待,如果是UDP來傳,就容易造成資料丟失,因此在這裡選擇了Web進行上傳,使用Web進行上傳是類比的Http Post上傳資料,當然,Post上傳資料的類,在網上找了一找,方式雖然很多,但是沒有一個感覺是我所使用的,所以參照原理之類的,進行了一下修改,算是做了一個參考。並且利用這個類完成了檔案和表彰的上傳服務。
具體代碼如下:
檔案與表單上傳類:
代碼
package com.UpLoadFileTest;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
public class PostFile {
//上傳代碼,第一個參數,為要使用的URL,第二個參數,為表單內容,第三個參數為要上傳的檔案,可以上傳多個檔案,這根據需要頁定
public static String post(String actionUrl, Map<String, String> params,
Map<String, File> files) throws IOException {
String BOUNDARY = java.util.UUID.randomUUID().toString();
String PREFIX = "--", LINEND = "\r\n";
String MULTIPART_FROM_DATA = "multipart/form-data";
String CHARSET = "UTF-8";
URL uri = new URL(actionUrl);
HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
conn.setReadTimeout(5 * 1000);
conn.setDoInput(true);// 允許輸入
conn.setDoOutput(true);// 允許輸出
conn.setUseCaches(false);
conn.setRequestMethod("POST"); //Post方式
conn.setRequestProperty("connection", "keep-alive");
conn.setRequestProperty("Charsert", "UTF-8");
conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA
+ ";boundary=" + BOUNDARY);
// 首先組拼文本類型的參數
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, String> entry : params.entrySet()) {
sb.append(PREFIX);
sb.append(BOUNDARY);
sb.append(LINEND);
sb.append("Content-Disposition: form-data; name=\""
+ entry.getKey() + "\"" + LINEND);
sb.append("Content-Type: text/plain; charset=" + CHARSET + LINEND);
sb.append("Content-Transfer-Encoding: 8bit" + LINEND);
sb.append(LINEND);
sb.append(entry.getValue());
sb.append(LINEND);
}
DataOutputStream outStream = new DataOutputStream(conn
.getOutputStream());
outStream.write(sb.toString().getBytes());
// 傳送檔案資料
if (files != null)
for (Map.Entry<String, File> file : files.entrySet()) {
StringBuilder sb1 = new StringBuilder();
sb1.append(PREFIX);
sb1.append(BOUNDARY);
sb1.append(LINEND);
sb1
.append("Content-Disposition: form-data; name=\"file\"; filename=\""
+ file.getKey() + "\"" + LINEND);
sb1.append("Content-Type: application/octet-stream; charset="
+ CHARSET + LINEND);
sb1.append(LINEND);
outStream.write(sb1.toString().getBytes());
InputStream is = new FileInputStream(file.getValue());
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
is.close();
outStream.write(LINEND.getBytes());
}
// 請求結束標誌
byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
outStream.write(end_data);
outStream.flush();
// 得到響應碼
int res = conn.getResponseCode();
InputStream in = conn.getInputStream();
InputStreamReader isReader = new InputStreamReader(in);
BufferedReader bufReader = new BufferedReader(isReader);
String line = null;
String data = "OK";
while((line = bufReader.readLine())==null)
data += line;
if (res == 200) {
int ch;
StringBuilder sb2 = new StringBuilder();
while ((ch = in.read()) != -1) {
sb2.append((char) ch);
}
}
outStream.close();
conn.disconnect();
return in.toString();
}
}
複製代碼
以上如果要寫入(上傳)資料,這裡使用的是out.write亦可使用out.wrtebyte(content)這樣子也可以,省得在這裡轉換了,交給系統進行轉換
這個可以根據個人的需要,加上等待條等等,如果要加上等待條的話,需要使用發送訊息的方式進行,這個是我所想到的,其它的方式沒有考慮好呢,有興趣的人可以自己加上去!我在這裡不再給增加了,增加的話,將在下載中添加一個下載的進度提示條。
實現內容如下:
代碼
Button btn1;
EditText view1;
EditText text1;
String SDPath = "/sdcard/";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
view1 = (EditText) findViewById(R.id.view1);
text1 = (EditText) findViewById(R.id.edit1);
btn1 = (Button) findViewById(R.id.btn1);
btn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
getFile();
try {
String name=URLEncoder.encode(text1.getText().toString(),"utf-8");
Map<String, String> params = new HashMap<String, String>();
params.put("NAME", name);
Map<String, File> files = new HashMap<String, File>();
files.put(getFile(), new File("/sdcard/"+getFile()));
view1.setText(PostFile.post("http://wdsl.recordinfo.tk/default.aspx", params, files));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
String getFile() {
File file = new File(SDPath);
File[] files = file.listFiles(new fileFilter());
String filename = "";
for (File file1 : files) {
filename = file1.getName();
}
Toast.makeText(this, filename, Toast.LENGTH_LONG).show();
return filename;
}
class fileFilter implements FilenameFilter {
@Override
public boolean accept(File dir, String filename) {
// TODO Auto-generated method stub
return filename.endsWith(".gif");
}
}
複製代碼
這些只是類裡面的內容,並且我只取了SD卡上的一張照片,因此我就在卡上放了一張照片,所以沒有進行列表處理,有興趣的話,可以自己添加上去,因為我主要是實現這一功能,對這一功能進行練習!
摘自 彬彬的部落格