SSM + Android 网络文件上传下载
SSM + Android 网络交互的那些事
在这里我用的是okHttp网络请求框架:https://github.com/square/okhttp(官方的开源库)
①ssm服务端的做法步骤:
1. 在 spring-servlet.xml 配置文件中加入下面的代码,用以通知spring加载文件上传处理器:
<!-- 定义文件上传处理器 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver"
p:defaultEncoding="UTF-8" />
2.ssm 控制器编写的映射关系:
@RequestMapping(value="user/postFile.action",method = RequestMethod.POST)
@ResponseBody
public String postFile(@RequestParam("file") MultipartFile file){
String name = file.getContentType();
System.out.println(name);
// if(file.isEmpty()){
//
// System.out.println("fial");
// //return "successful";
// }else{
// System.out.println("successful");
// //return "fail";
// }
return null;
3,记得加一个依赖库,commons-fileupload.jar 。如果用的是maven管理的话在pom.xml中加入下面依赖就好!
<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.2</version>
</dependency>
②android 通过okhttp上传文件(multipart form/data)
public Request postFile(String url,File file){ RequestBody fileBody = RequestBody.create(MediaType.parse("image/jpg"), file); MultipartBody.Builder builder = new MultipartBody.Builder(); builder.setType(MultipartBody.FORM) .addFormDataPart("file","welcome_crop.jpg",fileBody); RequestBody requestBody = builder.build(); Request request = new Request.Builder().url(url) .post(requestBody) .build(); return request; }
public void execute(final Request request, BaseCallBack callBack){ if(callBack == null){ callBack = BaseCallBack.CALLBACK_DEFAULT; } final BaseCallBack finalCallBack = callBack; client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { sendFailedResult(call,e,finalCallBack); } @Override public void onResponse(Call call, Response response) throws IOException { if (call.isCanceled()){ sendFailedResult(call,new Exception("response is canceled"),finalCallBack); return; } Log.d(TAG,""+response.code()); if (!finalCallBack.validateResponse(response)){ sendFailedResult(call,new Exception("response is failed"+response.code()),finalCallBack); return; } try { Object object = finalCallBack.parseResponse(response); sendSuccessResult(object,finalCallBack); }catch (Exception e){ e.printStackTrace(); }finally { if(response.body()!=null){ response.close(); } } } }); }
调用
Request fileRequest = OkHttpUtils.getInstance().postFile(url,file); OkHttpUtils.getInstance().execute(fileRequest, new MyStringCallBack());
https://github.com/ggyuer/ssmAndandroid(Android 端okhttp请求,服务端用自己的)
}