OKHttp3によるアップロード
Androidからサーバーへのアップロードがやりたくて2、3日苦労しました。
ボタンを押すとhtmlファイルをサーバーにアップロードするプログラム
GalleryActivity.java
package jp.wpblog.valletta.galleryactivity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.IOException;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class GalleryActivity extends AppCompatActivity implements View.OnClickListener {
private String TAG = "jp.wpblog.valletta.galleryactivity";
private Button mpickButton;
private TextView mtextView;
int RESULT_PICK_FILENAME = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gallery);
Button pickButton = (Button)findViewById(R.id.pickButton);
pickButton.setOnClickListener(this);
mpickButton = pickButton;
TextView textView = (TextView)findViewById(R.id.textView);
mtextView = textView;
}
public void onClick(View v) {
switch(v.getId()){
case R.id.pickButton:
getRequestWithPOST((Button)v);
break;
}
}
public void getRequestWithPOST(final Button button) {
button.setEnabled(false);
new AsyncTask<Void, Void, String>() {
@Override
protected String doInBackground(Void... params) {
String result = null;
// リクエストボディを作る
final MediaType TEXT = MediaType.parse("text/plain; charset=utf-8");
final String BOUNDARY = String.valueOf(System.currentTimeMillis());
RequestBody requestBody = new MultipartBody.Builder(BOUNDARY).setType(MultipartBody.FORM)
.addPart(Headers.of("Content-Disposition", "form-data; name=\"category\""),
RequestBody.create(TEXT, "GAME")
).addFormDataPart("upfile", "upfile.html", RequestBody.create(MediaType.parse("text/plain; charset=SJIS"),
"<HTML>\n" +
" <HEAD>\n" +
" <TITLE>タイトル</TITLE>\n" +
" </HEAD>\n" +
" <BODY>\n" +
" ボディ\n" +
" </BODY>\n" +
" </HTML>"))
.build();
// リクエストオブジェクトを作って
Request request = new Request.Builder()
.url("http://???.???.jp/php/upload.php")
.post(requestBody)
.build();
// クライアントオブジェクトを作る。
OkHttpClient client = new OkHttpClient();
// 実行。リクエストして結果を受け取る。
try {
Response response = client.newCall(request).execute();
result = response.body().string();
} catch (IOException e) {
e.printStackTrace();
}
// 返す
return result;
}
@Override
protected void onPostExecute(String result) {
button.setEnabled(true);
mtextView.setText(result);
Log.d(TAG, result);
}
}.execute();
}
}
activity_gallery.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Pick File from Gallery"
android:id="@+id/pickButton"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/pickButton"
android:text=""
android:id="@+id/textView"/>
</RelativeLayout>
manifest.xml
<uses-permission android:name="android.permission.INTERNET" />
build.gradle(app)
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:24.+'
compile 'com.squareup.okhttp3:okhttp:3.3.1'
}
そしてサーバー側のphpにまた苦労。
wordpressではうまくいかず別のページを開設しました。
(その間にwordpressが立ち上がらなくなり苛々、やっと復旧)
<?php
if (is_uploaded_file($_FILES["upfile"]["tmp_name"])) {
if (move_uploaded_file($_FILES["upfile"]["tmp_name"], "files/" . "upfile.html")) {
chmod("files/" . "upfile.html", 0644);
echo $_FILES["upfile"]["name"] . "をアップロードしました。";
} else {
// $_FILES['upfile']['error'] の値を確認
switch ($_FILES['upfile']['error']) {
case UPLOAD_ERR_OK: // OK
break;
case UPLOAD_ERR_NO_FILE: // ファイル未選択
$msg = 'ファイルが選択されていません';
case UPLOAD_ERR_INI_SIZE: // php.ini定義の最大サイズ超過
$msg = 'ファイルサイズが大きすぎます UPLOAD_ERR_INI_SIZE';
case UPLOAD_ERR_FORM_SIZE: // フォーム定義の最大サイズ超過
$msg = 'ファイルサイズが大きすぎます UPLOAD_ERR_FORM_SIZE';
break;
default:
$msg = 'その他のエラーが発生しました';
}
echo $msg;
}
} else {
// $_FILES['upfile']['error'] の値を確認
switch ($_FILES['upfile']['error']) {
case UPLOAD_ERR_OK: // OK
break;
case UPLOAD_ERR_NO_FILE: // ファイル未選択
$msg = 'ファイルが選択されていません';
case UPLOAD_ERR_INI_SIZE: // php.ini定義の最大サイズ超過
$msg = 'ファイルサイズが大きすぎます UPLOAD_ERR_NO_FILE';
break;
case UPLOAD_ERR_FORM_SIZE: // フォーム定義の最大サイズ超過
$msg = 'ファイルサイズが大きすぎます UPLOAD_ERR_FORM_SIZE';
break;
default:
$msg = 'その他のエラーが発生しました';
}
echo $msg;
}
ようやっと大きな山を越えた感じ!
ディスカッション
コメント一覧
まだ、コメントがありません