使用 http 上傳檔案

1 篇文章 / 0 new
author
使用 http 上傳檔案
下範例是使用 Android 提供的SDK進行 http的檔案上傳, 不必再使用外部 API
public class UploadUseHttp extends Activity {
    private final String lineEnd = "\r\n";
    private final String twoHyphens = "--";
    private final String boundary = "*shioulo****";//自行定義
    DataOutputStream doStream = null;
    private TextView tv;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        //
        tv = (TextView)findViewById(R.id.tv);
        httpFileUpload("/sdcard/01.mp3", "http://192.168.0.1/upload_file.php");
    }
    private void httpFileUpload(String selectedPath, String urlString) {                
        int maxBufferSize = 1024 * 1024;
        HttpURLConnection http = null;        
        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        //
        try {            
            // 建立 URL 連線
            URL url = new URL(urlString);
            // 開啟  HTTP 連線
            http = (HttpURLConnection) url.openConnection();
            // 設置是否對httpUrlConnection作輸出,因使用post請求,參數是存放在 http內,因此需要設為true, 預設為false;
            http.setDoInput(true);
            // 設置是否從httpUrlConnection讀入,預設為true
            http.setDoOutput(true);
            // Post 請求時不能使用快取
            http.setUseCaches(false);
            // 設定timeout時間
            http.setConnectTimeout(5000);
            http.setReadTimeout(20000);
            addMsg("網址/ip位置:"+java.net.Inet4Address.getByName(url.getHost()));
            // 設為POST方法,預設為GET
            http.setRequestMethod("POST");
            http.setRequestProperty("Connection", "Keep-Alive");
            // 指定編碼格式
            http.setRequestProperty("Accept-Charset", "utf-8");
            // file 上載準備
            FileInputStream fileInputStream = new FileInputStream(new File(selectedPath));
            http.setRequestProperty("Content-Type",    "multipart/form-data;boundary=" + boundary);
            // 上列設定必須要在connect之前完成            
            // 此處getOutputStream會內含connect呼叫(因此可以不用再呼叫 http.connect() )
            doStream = new DataOutputStream(http.getOutputStream());
            //
            doStream.writeBytes(twoHyphens + boundary + lineEnd);
            doStream.writeBytes("Content-Disposition: form-data; name=\"uploadfile\";filename=\"" + selectedPath + "\"" + lineEnd);
            doStream.writeBytes("Content-Type: application/octet-stream"+ lineEnd);
            doStream.writeBytes("Content-Transfer-Encoding: binary"+ lineEnd);
            doStream.writeBytes(lineEnd);
            // 建立 buffer
            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            buffer = new byte[bufferSize];
            // 準備資料
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
            while (bytesRead > 0) {
                doStream.write(buffer, 0, bufferSize);
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);
            }
            doStream.writeBytes(lineEnd);
            doStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);            
            fileInputStream.close();
 
            // 關閉Stream。此時,不能再向Stream輸出流寫入任何資料,先前寫入的資料存在於記憶體緩衝區中,
            // 在調用getInputStream()函數時正式把準備好的http請求發送到伺服器
            doStream.flush();
            doStream.close();
        } catch (MalformedURLException e) {
            addMsg(e.getMessage());
        } catch (IOException e) {        
            addMsg(e.getMessage());
        }
        // 讀取 server 回送訊息
        try {
            // 實際向server發送請求的程序是在呼叫 http.getInputStream()時
            // 呼叫過  http.getInputStream()後,當次的請求就結束,任何動作不會在傳送資料給server
            // 要再發送請求僅能重新重 new URL(urlString)再進行一次程序
            BufferedReader rd = new java.io.BufferedReader(
                      new InputStreamReader(http.getInputStream(), HTTP.UTF_8) );
            String str;
            while ((str = rd.readLine()) != null) {
                addMsg(str);
            }
            rd.close();
        } catch (IOException e) {
            addMsg(e.getMessage());
        }
    }
    private void addMsg(String data) {
        tv.append(data+"\n");
    }
}
Server端接收, PHP
//檔案儲存路徑
$uploadFilePath = "files/";
$target_path = $uploadFilePath . basename( $_FILES['uploadfile']['name']);
if(move_uploaded_file($_FILES['uploadfile']['tmp_name'], $target_path)) {
    echo "檔案 ".  basename( $_FILES['uploadfile']['name']). " 上傳完成\n";
} else{
    echo "檔案上傳錯誤\n";
}
Free Web Hosting