这个需要配合PHP使用
//需要在build.gradle添加 implementation 'com.squareup.okhttp3:okhttp:3.7.0' implementation 'com.squareup.okio:okio:1.13.0'
File file = new File(picturePath);
//上传文件的格式
String img_format = "image/*";
//封装文件格式
RequestBody requestFormat = RequestBody.create(MediaType.parse(img_format),file);
//文件内容
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("file",file.getName(),requestFormat)
.build();
//Okhttp网络数据传递
OkHttpClient client = new OkHttpClient.Builder()
.build();
Request request = new Request.Builder()
.url(链接)
.post(requestBody)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.i("onFailure",e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
Log.i("上传至服务器成功",response.body().string());
}
});
