版权声明:心灵泽尘 https://blog.csdn.net/github_38313789/article/details/83757272
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();
}
}
}