Android客户端使用OkGo上传文件或者图片,客户端和服务端代码分享

(一)上传单个文件或者图片:

客户端代码:

/**
 * 保存数据到服务器
 */
private void saveToInternet() {
    //上传单个文件
    String url = Constants.USER_NET_ICON;
    File  file = new File(filesDir, fileName);
    OkGo.<String>post(url)
            .tag(this)
            .params("icon", file)
            .isMultipart(true)
            .execute(new StringCallback() {
                @Override
                public void onSuccess(Response<String> response) {
                    LogUtil.e("上传成功" + response.body());
                }

                @Override
                public void onError(Response<String> response) {
                    LogUtil.e("上传失败" + response.body());
                }
            });

服务端代码:

   

@ResponseBody
	@RequestMapping("/icon")
	public Msg saveIcon(@RequestParam MultipartFile icon,HttpSession session)
			throws Exception {

		if (icon.getSize() > 0) {
			String path = session.getServletContext().getRealPath("/images");
			String fileName = icon.getOriginalFilename();
			File file = new File(path, fileName);			
			icon.transferTo(file);
                        //------其他数据库操作省略------            
			return Msg.success(null);
		}
		return Msg.fail();
	}

(二)上传多个文件或者图片:

客户端代码:

//上传多个文件
        List<File> files = new ArrayList<>();
        files.add(file);

        HttpParams param = new HttpParams();
        param.put("number", userNumber);
        String url = Constants.USER_NET_ICON;
        OkGo.<String>post(url)
                .tag(this)
                .isMultipart(true)
                .params(param)
                .addFileParams("files", files)
                .execute(此处省略回调方法...);

服务端代码:

// 上传多个文件
	@ResponseBody
	@RequestMapping(value="/uploadMore",method=RequestMethod.POST)
	public Msg uptestMost(@RequestParam MultipartFile[] files, @RequestParam String number,HttpSession session) throws Exception {
		String path = session.getServletContext().getRealPath("/images");		
		for (MultipartFile img : files) {
			if (img.getSize() > 0) {                
				String fileName = img.getOriginalFilename();
				File file = new File(path, fileName);
				img.transferTo(file);
				return Msg.success(null);
			}
		}
		return Msg.fail();
	}

猜你喜欢

转载自blog.csdn.net/qq_29644709/article/details/82799644