1. 程式人生 > >Android客戶端使用OkGo上傳檔案或者圖片,客戶端和服務端程式碼分享

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();
	}