前端上传图片
2018-06-20 本文已影响114人
墨色尘埃
之前总结过一篇图片上传的文章,
见客户端拍照上传服务器+保存到本地电脑。
list中包含了要上传的内容,当commitlist.size>0时,调用FormManager.uploadForm()方法,将commitlist传入(该方法中有两个回调,重写这两个回调方法)。
uploadForm()方法中:
①调用getFormFilePath()方法,获得forms的所有图片路径,并对路径进行编码方便批量上传;RetrofitCommon.genRequestBodyByFileName()方法将文件转成map...
②调用gson.toJsonTree(builds)方法将数据json化。
③最后调用Call<ResponseObj<Boolean>> call = buildApi.UpLoadBuild(buildsJson, requestBody);发起网络请求
MyTaskActivity
@Override
public void commitAll(final List<ListCommonItem> list) {
// Toast.makeText(this.getActivity(), "提交", Toast.LENGTH_SHORT).show();
// for (ListCommonItem each : list) {
// each.setStatus("已提交");
// }
if (list.size() <= 0) {
Toast.makeText(this, "请先勾选提交项", Toast.LENGTH_SHORT).show();
return;
}
final List<Form> commitlist = new ArrayList<>();
for (ListCommonItem eachitem : list) {
commitlist.add((Form) eachitem.getTag());
}
if (mProgress == null) {
mProgress = new ProgressDialog(this);
mProgress.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialogInterface) {
FormManager.cancelUpload();
}
});
}
mProgress.setTitle("上传进度");
mProgress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgress.setProgress(0);
mProgress.show();
mProgress.setMax(100);
if (commitlist.size() > 0) {
FormManager.uploadForm(commitlist, new IBooleanCall() {
@Override
public void call(boolean ok) {
if (ok) {
for (Form form : commitlist) {
form.setIsCommit(true);
DaoManager.getSession().getFormDao().update(form);
}
for (ListCommonItem listCommonItem : list) {
listCommonItem.setStatus("已提交");
}
dataChanged();
adapter.notifyDataSetChanged();
mProgress.dismiss();
Toast.makeText(MyTaskActivity.this, "提交成功", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MyTaskActivity.this, "提交失败", Toast.LENGTH_SHORT).show();
mProgress.dismiss();
}
}
}
, new UpLoadProgressInterceptor.UpLoadProgressListener() {
@Override
public void onRequestProgress(long bytesWritten, long contentLength) {
if (mProgress != null) {
double process = bytesWritten / (double) contentLength;
mProgress.setProgress((int) (process * 100));
}
}
}
);
}
}
FormManager
public static void uploadForm(List<Form> forms, final IBooleanCall iCall, UpLoadProgressInterceptor.UpLoadProgressListener listener) {
List<String> filePaths = new ArrayList<>();
ArrayList<String> fileKey = new ArrayList<>();
for (Form form : forms) {
HashMap<String, String> gFiles = getFormFilePath(form);
for (Map.Entry<String, String> each : gFiles.entrySet()) {
filePaths.add(each.getKey());
fileKey.add(each.getValue());
}
}
if (cacheRetrofit == null) {
cacheRetrofit = RetrofitUtil.getRetrofit(listener);
}
List<BuildingInfoFromServer> builds = new ArrayList<>();
for (Form form : forms) {
builds.add(BuildingInfoFromServer.getBuild(form));
}
Gson gson = new Gson();
JsonElement buildsJson = gson.toJsonTree(builds);
Map<String, RequestBody> requestBody = RetrofitCommon.genRequestBodyByFileName(filePaths, fileKey);
// gfilePaths=filePaths;
// gfileKey = fileKey;
BuildApi buildApi = cacheRetrofit.create(BuildApi.class);
Call<ResponseObj<Boolean>> call = buildApi.UpLoadBuild(buildsJson, requestBody);
// call.enqueue(new Callback<ResponseObj<Boolean>>() {
// @Override
// public void onResponse(Call<ResponseObj<Boolean>> call, Response<ResponseObj<Boolean>> response) {
//
// }
//
// @Override
// public void onFailure(Call<ResponseObj<Boolean>> call, Throwable t) {
//
// }
// });
RetrofitCommon.call(IApplication.mInstance, call, new IWebBooleanCall<Boolean>() {
@Override
public void call(boolean ok, Boolean data) {
if(ok){
iCall.call(true);
}
else{
iCall.call(false);
}
}
});
}
BuildApi,注意这里上传文件,使用@Multipart标签。@Part("builds")部分最后是从后台的HttpServletRequest request中通过String buildjson = mulRequest.getParameter("builds");拿到的。
@POST("build")
@Multipart
Call<ResponseObj<Boolean>> UpLoadBuild(@Part("builds") JsonElement buildList,
@PartMap Map<String, RequestBody> files);
对应后台control里的BuildController
@RequestMapping(method = RequestMethod.POST)
public ResponseObj<Boolean> UpLoad(HttpServletRequest request) throws Exception{
if (request instanceof MultipartHttpServletRequest) {
MultipartHttpServletRequest mulRequest = (MultipartHttpServletRequest) request;
Set<Map.Entry<String, MultipartFile>> set = mulRequest.getFileMap().entrySet();
String buildjson = mulRequest.getParameter("builds");
ObjectMapper oMapper = new ObjectMapper();
List<Build> builds = null;
try {
builds = oMapper.readValue(buildjson, new TypeReference<List<Build>>() {
});
} catch (IOException e) {
return new ResponseObj<>(false, new RetCode("数据格式不正确"));
}
for (Build build : builds) {
mapper.deleteByPrimaryKey(build.getBldId());
build.setUpdateTime(new Date());
mapper.insertBuild(build);
filemapper.deleteFile(build.getBldId());
}
for (Map.Entry<String, MultipartFile> each : set) {
String fileId = UUID.randomUUID().toString();
String fileName = each.getKey();
String[] vars = fileName.split("\\|\\|");
if (vars.length != 3) {
return new ResponseObj<>(false, new RetCode("格式不正确"));
} else {
String bId = vars[0];
String groupName = vars[1];
fileName = vars[2];
uploadFile(ftpIp, ftpPort, ftpUserName, ftpPassword, "/AC", fileId + fileName.substring(fileName
.lastIndexOf(".")), each.getValue().getInputStream());
UploadFile upload = new UploadFile();
upload.setC_TRX_REF(bId);
upload.setFILE_NAME(fileId);
upload.setO_FILE_NAME(fileName);
upload.setFILE_TYPE(fileName.substring(fileName.lastIndexOf(".") + 1));
upload.setFILE_REMARK_TWO(groupName);
upload.setUPDATE_TIME(new Date());
try {
filemapper.insertFile(upload);
} catch (Exception e) {
log.error("RetCode class {}", getClass(), e);
return new ResponseObj<>(false, new RetCode("文件数据库记录出错"));
}
}
}
return new ResponseObj<>(true, RetCode.SUCCESS);
} else {
return new ResponseObj<>(true, RetCode.FAIL);
}
}
参见前端E:\ASProject\zhcnapp_v1项目:MyTaskActivity类P71行,FormManager类P62行;后台E:\IDEAProject\zhcnserver_v2BuildController类P186行