2020-05-08 Java后台工程Okhttp方式上传文件示
2020-05-08 本文已影响0人
gdlooker
参考示例:http://www.360doc.com/content/18/0409/18/8335678_744234144.shtml
java后端工程一 或者Android端 示例代码
package cn.gdchent.springbootsecurity.utils;
import okhttp3.*;
import java.io.File;
import java.io.IOException;
/**
* 文件上传
* http://www.360doc.com/content/18/0409/18/8335678_744234144.shtml
*/
public class OkHttpUploadUtils {
// 使用OkHttp上传文件
public static void uploadFile(File file) {
OkHttpClient client = new OkHttpClient();
MediaType contentType = MediaType.parse("application/octet-stream"); // 上传文件的Content-Type
RequestBody fileBody = RequestBody.Companion.create(contentType, file); // 上传文件的请求体
RequestBody requestBody=new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("file","test.txt",fileBody)
.build();
Request request = new Request.Builder()
.url("http://192.168.120.58:8086/uploadFile") // 上传地址
.post(requestBody)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) throws IOException {
// 文件上传成功
if (response.isSuccessful()) {
System.out.println("onResponse: " + response.body().string());
} else {
System.out.println("onResponse: " + response.message());
}
}
@Override
public void onFailure(Call call, IOException e) {
// 文件上传失败
System.out.println("onFailure: " + e.getMessage());
}
});
}
}
spring boot 工程后端接收代码如下:
@PostMapping(path = "/uploadFile", produces = {"multipart/form-data","application/octet-stream"})
@ResponseBody
public HttpResultMap uploadFile(@RequestParam(value = "file") MultipartFile file){
System.out.println("后端响应");
//before文件夹根路径
String uploadDirPath= ResourceFilePathUtils.ipaBeforeRootPath+ File.separator;
File uploadDir=new File(uploadDirPath);
if(!uploadDir.exists()){
uploadDir.mkdirs();
}
String uploadFileName=file.getOriginalFilename();
System.out.println("uploadFileName:"+uploadFileName);
//如果这个文件存在了
File uploadFile=new File(uploadDir,uploadFileName);
if(uploadFile.exists()){
uploadFile.delete(); //先删除再创建
}
//文件不存在 创建文件 然后写入数据到文件
try {
uploadFile.createNewFile();//创建文件
Path path= Paths.get(uploadFile.getAbsolutePath());
byte [] bytes=file.getBytes();
Files.write(path,bytes);
} catch (IOException e) {
e.printStackTrace();
}finally {
return new HttpResultMap(
200,
"message",
new JSONObject().put("data","data")
);
}
}