Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

CodeIgniter + Volley 實現多圖片上傳(含服務端、Web 與 Android 完整代碼)

編輯:關於 Android 程式設計

問題背景:App 在加載圖片時,往往還需要同時傳遞參數,並支持一次上傳多張圖片。本文以已配好 CodeIgniter 框架的服務端為例(不用該框架其實也無妨),完整演示服務端、Web 測試頁與 Android 客戶端三部分的實現。

一、服務端部分

1. 新建 upload_helper.php

在 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;
}

說明:

  • 注意其中的 key 為 f_file,這就要求 App 或 Web 在上傳、建表單時把這個值對應上。
  • 該文件主要遍歷 $_FILES,通過 current 取到當前 file 的信息並轉存到數組,注意轉存後索引從 1 開始;轉存字段包括 name/type/tmp_name/error/size,用 next 移動指針。

2. 新建 upload_form.php(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" />

說明:

  • 這裡用 CI 框架的 form_open_multipart 建了一個 multipart 表單,訪問的是 upload 控制器裡的 web_upload 方法;第三個參數 $data 用於模擬向服務端傳遞的 POST 參數,你也可以再補幾個 input。
  • input 的 name 對應 f_file[],與服務端約定一致。
  • 要支持多文件上傳就加上 multiple="multiple",否則一次只能傳一個。

3. 新建 upload_success.php

在 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 的數據。

4. 核心控制器 Upload.php

在 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;
    }
}
?>

解釋如下:

  • Upload 繼承自 BASE_CI_Controller(也可換成 CI_Controller),基類裡封裝了項目常用的安全校驗邏輯。
  • m_type 記錄上傳類型,m_id 是圖片所屬對象的 id,m_path 是路徑(可按 type 區分),m_error 記錄錯誤;構造函數裡把需要的 helper 都 load 進來,若不需要操作數據庫的 Picture_model 可注釋掉。
  • app_upload() 暴露給 App 使用:先 init_argc() 初始化 POST 參數,再調 multifile_array() 遍歷上傳,最後根據 m_error 是否為空決定返回什麼消息。Util::random_str() 是對時間戳做 md5,防止文件名重複。
  • Util 相關代碼:
public static function token() {
    $curr = Util::time();
    return md5($curr);
}
public static function random_str() {
    return Util::token();
}
  • 每次上傳成功後調 on_upload_success()、失敗調 on_upload_error() 做數據庫更新等操作,其中 on_upload_success() 接收 $upload_data['file_name'] 即上傳後的文件名。
  • web_upload() 給 Web 上傳用,通過 do_upload2() 上傳成功後加載一個 view 展示結果。注意要保證目的文件夾有可寫權限。

先用 Web 測試效果:https://localhost/~yanzi/city52/index.php/upload

二、客戶端:基於 Volley 的多文件上傳封裝

客戶端相對簡單,基於 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 三端的多圖片上傳就全部打通了。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved