flutter 上传图片 我是按照dio官方的代码写的 但是服
2019-07-03 本文已影响5人
雪纳瑞的哈士奇
flutter 上传图片 我是按照dio官方的代码写的 但是服务器接收不到,真是够够的~~~
我们两个用了很多种办法 测试 搞了一天半 终于搞出来了
老规矩 废话不多说 直接上代码
flutter 代码
上传代码
HttpHelper httpHelper = new HttpHelper();
httpHelper.controller = value.changeAvatarC;
httpHelper.action = value.changeAvatarA;
String path = imageFile.path;
var name = path.substring(path.lastIndexOf("/") + 1, path.length);
var suffix = name.substring(name.lastIndexOf(".") + 1, name.length);
FormData formData = FormData.from({
"username":widget.model.username,
"file":new UploadFileInfo(new File(path), name,contentType: ContentType.parse("image/$suffix")),
});
httpHelper.post(data: formData).then((m){
func();
if(m == 3){
Fluttertoast.showToast(msg: "修改成功");
Navigator.pop(context);
}
});
httphelper 里面的post代码
/*
* post请求
*/
Future<dynamic> post({data, Options options, cancelToken}) async {
Response response;
if(data == null){
data = new FormData();
}
String url = builder();
data[value.login_token] = await Tool().getString(value.token);
print("post url =====================$url params =============== $data");
print("options ===================== $options");
try {
response = await dio.post(url, data: data, options: options, cancelToken: cancelToken);
print('post success---------${response.data}');
} on DioError catch (e) {
print('post error---------$e');
formatError(e);
return null;
}
return response.data;
}
java代码(我的后台是java)
Part part = request.getPart("file");
String fileNames = getFileName(part);
String path = writeTo(fileNames,part,nowDate);
private String getFileName(Part part) {
String head = part.getHeader("Content-Disposition");
String fileName = head.substring(head.indexOf("filename=\"")+10, head.lastIndexOf("\""));
System.out.println(fileName);
return fileName;
}
private String writeTo(String fileName, Part part,String nowDate)throws IOException {
String addAndFilename = "/"+"upload" + "/" + nowDate + "/";
filesPath=filesPath.replace("file:","");
String finalPath = filesPath + addAndFilename;
if (!new File(finalPath).exists() || !new File(finalPath).isDirectory()) {
new File(finalPath).mkdirs();
}
InputStream in = part.getInputStream();
OutputStream out = new FileOutputStream(finalPath+fileName);
byte[] b = new byte[1024];
int length = -1;
while((length = in.read(b))!=-1){
out.write(b, 0, length);
}
in.close();
out.close();
return finalPath+fileName;
}
他告诉我这是个非常冷门的东西 基本上很少用 如果大胸弟们需要其他的代码 评论区找我 我知无不言言无不尽