Android核心技術-day05-02-檔案上傳
阿新 • • 發佈:2018-11-07
package com.gaozewen.fileupload; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.text.TextUtils; import android.view.View; import android.widget.EditText; import android.widget.Toast; import com.gaozewen.fileupload.http.AsyncHttpClient; import com.gaozewen.fileupload.http.AsyncHttpResponseHandler; import com.gaozewen.fileupload.http.RequestParams; import org.apache.http.Header; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; public class MainActivity extends AppCompatActivity { private EditText mEt_path; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mEt_path = (EditText) findViewById(R.id.et_path); // 建立一個檔案 try { File file = new File(getCacheDir(), "upload.txt"); BufferedWriter writer = new BufferedWriter(new FileWriter(file)); writer.write("upload"); writer.newLine(); writer.flush(); } catch (Exception e) { e.printStackTrace(); } } public void upload(View view) { String path = mEt_path.getText().toString().trim(); if(TextUtils.isEmpty(path)){ Toast.makeText(this,"路徑不能為空", Toast.LENGTH_SHORT).show(); return; } File file = new File(path); if (file.exists() && file.length() > 0) { try { AsyncHttpClient client = new AsyncHttpClient(); RequestParams params = new RequestParams(); params.put("profile_picture",file); client.post("http://192.168.1.102:8080/upload", params, new AsyncHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) { Toast.makeText(MainActivity.this,"上傳成功", Toast.LENGTH_SHORT).show(); } @Override public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) { Toast.makeText(MainActivity.this,"上傳失敗", Toast.LENGTH_SHORT).show(); } }); } catch (Exception e) { e.printStackTrace(); Toast.makeText(MainActivity.this,"上傳失敗", Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(this,"檔案不存在或者內容為空", Toast.LENGTH_SHORT).show(); } } }