Android上传图片到服务器文件夹的实现方式一般有两种,一种是通过HttpURLConnection实现,另一种则是使用第三方框架,例如OkHttp、Retrofit等。以下是HttpURLConnection的实现示例。
① 服务端编写代码 在服务端创建对应文件夹,这里/uploadfile”为例,下面的代码实现了上传文件,并返回上传成功的提示信息:
② 客户端编写代码 在客户端通过HttpURLConnection发送POST请求,将上传的文件写入到输出流中。下面的示例代码,通过调用uploadFile方法完成图片上传操作:
public class MainActivity extends AppCompatActivity { private Button btnUpload; private TextView tvResult; private String url = "http://192.168.1.104:8080/upload.php"; private File upLoadFile;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initViews();
setListeners();
}
private void initViews() {
btnUpload = findViewById(R.id.btn_upload);
tvResult = findViewById(R.id.tv_result);
}
private void setListeners() {
btnUpload.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new Thread(new Runnable() {
@Override
public void run() {
uploadFile(upLoadFile);
}
}).start();
}
});
}
/**
* 上传本地文件
* @param file 本地文件
*/
private void uploadFile(File file) {
HttpURLConnection conn = null;
DataOutputStream dos = null;
String BOUNDARY = "---------------------------123821742118716"; // 边界标识符
String PREFIX = "--", LINE_END = "\r\n";
String CHARSET = "UTF-8";
try {
URL url = new URL(this.url);
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(5000);
conn.setConnectTimeout(5000);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Charset", CHARSET);
conn.setRequestProperty("