編輯:關於 Android 程式設計
在 Android 上實現檔案上傳其實並不難,原理與 Java 中的上傳如出一轍,核心都在於熟練操作輸入流與輸出流。此外還有一個至關重要的環節,就是 Content-Type 等參數的配置——只要把這些都準備妥當,上傳就水到渠成了。下面是我撰寫的一個上傳工具類:
package com.spring.sky.image.upload.network;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.UUID;
import android.util.Log;
/**
* 上傳工具類
*/
public class UploadUtil {
private static final String TAG = "uploadFile";
private static final int TIME_OUT = 10 * 1000; // 超時時間
private static final String CHARSET = "utf-8"; // 設置編碼
/**
* android 上傳檔案到伺服器
* @param file 需要上傳的檔案
* @param RequestURL 請求的 url
* @return 返回響應的內容
*/
public static String uploadFile(File file, String RequestURL) {
String result = null;
String BOUNDARY = UUID.randomUUID().toString(); // 邊界標識,隨機生成
String PREFIX = "--", LINE_END = "\r\n";
String CONTENT_TYPE = "multipart/form-data"; // 內容類型
try {
URL url = new URL(RequestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(TIME_OUT);
conn.setConnectTimeout(TIME_OUT);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Charset", CHARSET);
conn.setRequestProperty("connection", "keep-alive");
conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);
if (file != null) {
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
StringBuffer sb = new StringBuffer();
sb.append(PREFIX);
sb.append(BOUNDARY);
sb.append(LINE_END);
// name 的值為服務端需要的 key,只有這個 key 才能取得對應檔案
sb.append("Content-Disposition: form-data; name=\"img\"; filename=\"" + file.getName() + "\"" + LINE_END);
sb.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINE_END);
sb.append(LINE_END);
dos.write(sb.toString().getBytes());
InputStream is = new FileInputStream(file);
byte[] bytes = new byte[1024];
int len = 0;
while ((len = is.read(bytes)) != -1) {
dos.write(bytes, 0, len);
}
is.close();
dos.write(LINE_END.getBytes());
byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END).getBytes();
dos.write(end_data);
dos.flush();
int res = conn.getResponseCode();
Log.e(TAG, "response code:" + res);
InputStream input = conn.getInputStream();
StringBuffer sb1 = new StringBuffer();
int ss;
while ((ss = input.read()) != -1) {
sb1.append((char) ss);
}
result = sb1.toString();
Log.e(TAG, "result : " + result);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
}這個工具類只需要傳入一個 File 檔案與一個上傳的請求 URL 即可。不過要特別提醒:由於用到了網絡請求,大家可別忘了在 Android 客戶端加上訪問網絡的權限!
另外還有一點值得注意:由於本人是做服務端 JavaEE 的,我發現上傳過程中,如果檔案的標識 name 剛好是 Java 關鍵字之類的字串,往往會引發不少莫名其妙的問題。因此大家在命名時盡量避開關鍵字。
下面是 Activity 的程式碼:
package com.spring.sky.image.upload;
import java.io.File;
import com.spring.sky.image.upload.network.UploadUtil;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends Activity implements OnClickListener {
private static final String TAG = "uploadImage";
private static String requestURL = "https://192.168.1.14:8080/SetBlobData/img!up";
private Button selectImage, uploadImage;
private ImageView imageView;
private String picPath = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
selectImage = (Button) this.findViewById(R.id.selectImage);
uploadImage = (Button) this.findViewById(R.id.uploadImage);
selectImage.setOnClickListener(this);
uploadImage.setOnClickListener(this);
imageView = (ImageView) this.findViewById(R.id.imageView);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.selectImage:
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, 1);
break;
case R.id.uploadImage:
File file = new File(picPath);
if (file != null) {
String request = UploadUtil.uploadFile(file, requestURL);
uploadImage.setText(request);
}
break;
default:
break;
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
Uri uri = data.getData();
try {
String[] pojo = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, pojo, null, null, null);
if (cursor != null) {
ContentResolver cr = this.getContentResolver();
int colunm_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String path = cursor.getString(colunm_index);
// 判斷檔案後綴,只接受圖片格式
if (path.endsWith("jpg") || path.endsWith("png")) {
picPath = path;
Bitmap bitmap = BitmapFactory.decodeStream(cr.openInputStream(uri));
imageView.setImageBitmap(bitmap);
} else {
alert();
}
} else {
alert();
}
} catch (Exception e) {
}
}
super.onActivityResult(requestCode, resultCode, data);
}
private void alert() {
Dialog dialog = new AlertDialog.Builder(this)
.setTitle("提示")
.setMessage("您選擇的不是有效的圖片")
.setPositiveButton("確定", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
picPath = null;
}
}).create();
dialog.show();
}
}layout 程式碼:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="選擇圖片"
android:id="@+id/selectImage"
/>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="上傳圖片"
android:id="@+id/uploadImage"
/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
/>
</LinearLayout>以上就是 Android 上傳圖片的全部程式碼。若想上傳其他類型的檔案,只要修改過濾條件即可,同時務必確保檔案類型與服務端保持一致,否則上傳就會失敗。如果在使用過程中遇到任何問題,歡迎與我交流。學習在於積累!
WebView 中介紹 JavaScript 與 Java 雙向調用的完整實踐
混合開發中經常需要網頁調用原生能力,比如拍照、選相冊、錄音。Android 的 WebView 基於 WebKit 內核,內建了 JS 與 Java 互調的接口,接入並不
Android 系統源碼解析:ActivityManagerService(AMS)的角色與通信機制
在多篇文章中我們都提到過 ActivityManagerService。它是系統啟動時加載的一個服務線程,運行在 system_server 進程中,主要負責管理系統中的
Android 平板自製鍵盤:用 PopupWindow 實現左下角彈窗輸入(仿微信密碼鍵盤)
先前幾篇文章裡,我曾經介紹過如何調用 Google 提供的鍵盤相關 API 來自訂鍵盤。這種做法有個明顯的限制:自訂鍵盤只能佔滿整個螢幕,無法滿足「只佔用畫面一部分」這類
《Android 從入門到精通》第 17 篇:ProgressBar 進度條完全解析
凡是需要「讓使用者等一等」的場景,幾乎都離不開進度條。本文延續《Android 從入門到精通》的系列進度,把 ProgressBar 的類別結構、常用方法與一個可直接跑起