安卓端代码:
public static void sendFile(String filePath){
//要发送的文件
File file = new File(filePath);
OkHttpClient client = new OkHttpClient.Builder().build();
//构建multipart body
MultipartBody body = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("username", "wjj")
.addFormDataPart("file", file.getName(), RequestBody.create(MediaType.parse("image/jpeg"), file))
.build();
Request request = new Request.Builder()
.headers(headerBuilder.build())
.url("http://10.237.54.146:8866/test/uploadbin")
.post(body)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(@NonNull Call call, @NonNull IOException e) {
Log.e("wjj", "call res = " + "failed");
}
@Override
public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
Log.e("wjj", "response = " + response.body().string());
}
});
}
springboot端代码
@PostMapping("/uploadbin")
public String recvFile(MultipartHttpServletRequest request) throws Exception {
FileInputStream sin = (FileInputStream) request.getFile("file").getInputStream();
File file = new File("D:/Tmp/saved.jpg");
FileOutputStream fos = new FileOutputStream(file);
byte[] bytes = new byte[1024];
int len = -1;
while((len = sin.read(bytes)) != -1){
fos.write(bytes, 0, len);
}
sin.close();
fos.close();
return "file len:" + ", " + request.getContentType();
}
Multipart中的其他数据是如何取出的?
比如这段:
其实也是通过读取流:
byte[] bytes1 = request.getPart("username").getInputStream().readAllBytes();
String s = new String(bytes1);
System.out.println(s);
那么multipart中的文件名是如何取出的?
方法:
request.getFile("file").getOriginalFilename()