SpringMVC+Volley实现Android端上传文件

Android端使用的是Volley的Request基类,实现它的几个方法,以拼接表单的方式来上传文件

服务器端则是采用Spring框架来接收文件。

一、Android:三个类:MainActivity,PostRequest,UploadFileRequest.

1.PostRequest继承自Request,实现它的deliverResponseparseNetworkResponse以及getParams三个方法,

构造函数为

 
  
public PostRequest(String url,Mapparams, ResponseListener listener){...}



2.UploadFileRequest继承自PostRequest,实现其getBody()和getBodyContentType()方法,getBody来拼接表单数据,getBodyContentType用来返回表单类型:

 
  
return "multipart/form-data;boundary=------8d74g45h";
构造函数为
 
  
public UploadFileRequest(String url, ListfileList, ResponseListener listener){...}
3.在MainActivity中调用UploadFileRequest,并添加到Volley队列中。
 
  
uploadFileRequest = new UploadFileRequest(url, fileForms, new ResponseListener() {
    @Override
    public void onErrorResponse(VolleyError volleyError) {
        Toast.makeText(MainActivity.this, "上传失败", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onResponse(Object o) {
        Toast.makeText(MainActivity.this, "上传成功", Toast.LENGTH_SHORT).show();
    }
});

Volley.newRequestQueue(MainActivity.this).add(uploadFileRequest);
二、服务器端:
@Controller
public class UploadController {

    @RequestMapping("uploadImage")
    //@ResponseBody
    public void addImage(HttpServletRequest request) throws IllegalStateException, IOException{
        MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
        MultipartFile file = multipartHttpServletRequest.getFile("uploadfile");
        if(!file.getOriginalFilename()==null){
            File targetFile = new File("F:/789.png");
            file.transferTo(targetFile);
        }

    }


使用MultipartHttpServletRequest 的时候要记得在spring配置文件中添加Multipart的解析器:
@Controller
public class UploadController {

    @RequestMapping("uploadImage")
    //@ResponseBody
    public void addImage(HttpServletRequest request) throws IllegalStateException, IOException{
        MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
        MultipartFile file = multipartHttpServletRequest.getFile("uploadfile");
        if(!file.getOriginalFilename()==null){
            File targetFile = new File("F:/789.png");
            file.transferTo(targetFile);
        }

    }


这样就完成了文件上传的操作。
参考:
1.Spring文件上传处理:http://amcucn.iteye.com/blog/264457
2.Volley文件上传操作:http://blog.csdn.net/jxxfzgy/article/details/44064481
 
  

你可能感兴趣的:(服务器,Android)