編輯:關於 Android 程式設計
問題背景:App 在加載圖片時,往往還需要同時傳遞參數,並支持一次上傳多張圖片。本文以已配好 CodeIgniter 框架的服務端為例(不用該框架其實也無妨),完整演示服務端、Web 測試頁與 Android 客戶端三部分的實現。
在 controllers 下的 helpers 目錄新建 upload_helper.php:
<?php
/**
* Make multifile array input complaint with CI_Upload.
* For use files[ ] input name you must use it method.
*
* @author porquero
*
* @example
* In Controller
* $this->load->helper('upload');
* multifile_array();
* foreach ($_FILES as $file => $file_data) {
* $this->upload->do_upload($file);
* ...
* }
*/
function multifile_array() {
if (count($_FILES) == 0) return;
$files = array();
$all_files = $_FILES['f_file']['name'];
$i = 0;
foreach ((array)$all_files as $filename) {
$files[++$i]['name'] = $filename;
$files[$i]['type'] = current($_FILES['f_file']['type']); next($_FILES['f_file']['type']);
$files[$i]['tmp_name'] = current($_FILES['f_file']['tmp_name']); next($_FILES['f_file']['tmp_name']);
$files[$i]['error'] = current($_FILES['f_file']['error']); next($_FILES['f_file']['error']);
$files[$i]['size'] = current($_FILES['f_file']['size']); next($_FILES['f_file']['size']);
}
$_FILES = $files;
}
說明:
f_file,這就要求 App 或 Web 在上傳、建表單時把這個值對應上。在 views 裡新建 upload_form.php,用來在 Web 上模擬測試上傳:
<?php echo $error;?>
<?php $data = array('type'=>'shop', 'id'=>'1');?>
<?php echo form_open_multipart('upload/web_upload', '', $data);?>
<input multiple="multiple" name="f_file[]" size="20" type="file" /><br /><br />
<input type="submit" value="upload" />
說明:
form_open_multipart 建了一個 multipart 表單,訪問的是 upload 控制器裡的 web_upload 方法;第三個參數 $data 用於模擬向服務端傳遞的 POST 參數,你也可以再補幾個 input。f_file[],與服務端約定一致。multiple="multiple",否則一次只能傳一個。在 views 下新建上傳成功後的展示頁:
<h3>Your file was successfully uploaded!</h3>
<ul>
<?php foreach ($upload_data as $item => $value):?>
<li><?php echo $item;?>: <?php echo $value;?></li>
<?php endforeach; ?>
</ul>
<p><?php echo anchor('upload', 'Upload Another File!'); ?></p>
其中 $upload_data 是控制器上傳成功後傳給 view 的數據。
在 controllers 文件夾下新建 Upload.php,這是最核心的上傳控制器:
<?php
require_once APPPATH . 'controllers/base/BASE_CI_Controller.php';
class Upload extends BASE_CI_Controller {
private $m_type = '';
private $m_id = '';
private $m_path = './application/cache/image';
private $m_error = array();
public function __construct() {
parent::__construct();
$this->load->helper(array('form', 'url', 'upload'));
//$this->load->model('picture_model');
}
public function index() {
$this->load->view('upload_form', array('error' => ' '));
}
public function app_upload() {
$this->init_argc();
multifile_array();
foreach ($_FILES as $file => $file_data) {
$this->do_upload($file);
}
if ($this->m_error == NULL || count($this->m_error) == 0) {
$this->output->set_output(json_encode(array('msg' => '上傳成功')));
} else {
$this->output->set_output(json_encode($this->m_error));
}
}
public function do_upload($file) {
$config['upload_path'] = $this->m_path;
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['max_size'] = 10240;
$config['max_width'] = 2000;
$config['max_height'] = 2000;
$config['file_name'] = Util::random_str();
$this->load->library('upload', $config);
if (! $this->upload->do_upload($file)) {
$this->on_upload_error($this->upload->display_errors());
} else {
$upload_data = $this->upload->data();
$this->on_upload_success($upload_data['file_name']);
}
}
public function web_upload() {
multifile_array();
foreach ($_FILES as $file => $file_data) {
$this->do_upload2($file);
}
}
private function init_argc() {
$this->m_type = $this->getPost('type');
$this->m_id = $this->getPost('id');
$this->m_path = $this->getPath($this->m_type);
}
private function getPath($type) {
$path = './application/cache/image/shop';
if ($type == 'shop') {
$path = './application/cache/image/shop';
}
return $path;
}
private function on_upload_success($name) {
if ($this->m_type == 'shop') {
//$this->picture_model->add_shop_picture($this->m_id, $this->m_type, $name);
} else if ($this->m_type == 'avatar') {
//$this->picture_model->add_user_avatar($this->m_id, $this->m_type, $name);
}
}
private function on_upload_error($error) {
$this->m_error['msg'] = $error;
}
}
?>
解釋如下:
app_upload() 暴露給 App 使用:先 init_argc() 初始化 POST 參數,再調 multifile_array() 遍歷上傳,最後根據 m_error 是否為空決定返回什麼消息。Util::random_str() 是對時間戳做 md5,防止文件名重複。public static function token() {
$curr = Util::time();
return md5($curr);
}
public static function random_str() {
return Util::token();
}
web_upload() 給 Web 上傳用,通過 do_upload2() 上傳成功後加載一個 view 展示結果。注意要保證目的文件夾有可寫權限。先用 Web 測試效果:https://localhost/~yanzi/city52/index.php/upload

客戶端相對簡單,基於 Volley 封裝了一個 MultipartRequest.java:
package com.android.nomnom.volley;
import android.util.Log;
import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.HttpHeaderParser;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MultipartRequest extends Request<String> {
private MultipartEntity entity = new MultipartEntity();
private Response.Listener<String> mListener;
private List<File> mFileParts;
private String mFilePartName;
private Map<String, String> mParams;
// 單個文件 + 參數上傳
public MultipartRequest(String url, Response.Listener<String> listener,
Response.ErrorListener errorListener, String filePartName, File file,
Map<String, String> params) {
super(Method.POST, url, errorListener);
mFileParts = new ArrayList<File>();
if (file != null && file.exists()) {
mFileParts.add(file);
} else {
VolleyLog.e("MultipartRequest---file not found");
}
mFilePartName = filePartName;
mListener = listener;
mParams = params;
buildMultipartEntity();
}
// 多個文件 + 參數上傳
public MultipartRequest(String url, Response.Listener<String> listener,
Response.ErrorListener errorListener, String filePartName,
List<File> files, Map<String, String> params) {
super(Method.POST, url, errorListener);
mFilePartName = filePartName;
mListener = listener;
mFileParts = files;
mParams = params;
buildMultipartEntity();
}
@Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String parsed;
try {
parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
} catch (UnsupportedEncodingException e) {
parsed = new String(response.data);
}
return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response));
}
@Override
protected void deliverResponse(String response) {
mListener.onResponse(response);
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = super.getHeaders();
if (headers == null || headers.equals(Collections.emptyMap())) {
headers = new HashMap<String, String>();
}
return headers;
}
@Override
public String getBodyContentType() {
return entity.getContentType().getValue();
}
@Override
public byte[] getBody() throws AuthFailureError {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
entity.writeTo(bos);
} catch (IOException e) {
VolleyLog.e("IOException writing to ByteArrayOutputStream");
}
return bos.toByteArray();
}
private void buildMultipartEntity() {
if (mFileParts != null && mFileParts.size() > 0) {
for (File file : mFileParts) {
entity.addPart(mFilePartName, new FileBody(file));
}
long l = entity.getContentLength();
Log.i("YanZi-volley", mFileParts.size() + "個,長度:" + l);
}
try {
if (mParams != null && mParams.size() > 0) {
for (Map.Entry<String, String> entry : mParams.entrySet()) {
entity.addPart(entry.getKey(),
new StringBody(entry.getValue(), Charset.forName("UTF-8")));
}
}
} catch (UnsupportedEncodingException e) {
VolleyLog.e("UnsupportedEncodingException");
}
}
}
使用時 new 一個 request,然後把它 add 到 queue 裡就可以了。至此,服務端、Web 與 Android 三端的多圖片上傳就全部打通了。
Android 藍牙即時通訊實作:客戶端與伺服器端設計
藍牙即時通訊是 Android 開發中常見的應用主題,尤其適合用於設備配對、短距離資料交換與穿戴裝置互動。本文以一個簡易 Demo 為例,說明如何透過藍牙 RFCOMM
Android 微信自動搶紅包插件的優化與實作思路
本文僅從技術研究角度,探討 Android 自動化服務與無障礙功能的應用。此類功能會依賴系統通知、無障礙服務與特定 App 版本,實際使用時需注意平台規範與使用者授權。
微信應用號是什麼?小程序內測信息一次看懂
一段時間裡,關於微信應用號的討論越來越多。傳聞已久的應用號終於有了實質動靜——有网友在微博曬出了一張微信應用號內測邀請函,引來大量轉發與猜測。那麼,微信應用號究竟是什麼?
Android 對稱加密與非對稱加密入門詳解
凱撒密碼1. 介紹凱撒密碼是最古老的對稱加密體制之一,在古羅馬時期就已流行。基本思想是透過把字母移動固定位數來實現加解密。例如偏移量為 3 時,A 變 D、B 變 E,而