Android开发随想(2)

              上次我们的框架进行到文件上传的部分:

               话不多说:看代码

        /**
	 * 文件上传采用MultipartPostMethod
	 * @param url   服务器地址
	 * @param files  目标文件
	 * @notice 支持多文件上传
	 * @return JSON数据
	 * @throws Exception 
	 */
	@SuppressWarnings("deprecation")
	public static String fileUpload(String url,List<File> files) throws Exception{
		String response = null;
		if(null != url && !"".equals(url)){
			if(null!=files && files.size()>0){
				mHttpClient = new HttpClient();
				mHttpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
				mHttpClient.getParams().setUriCharset("UTF-8");
				MultipartPostMethod method = new MultipartPostMethod(url);
				
				//处理文件
				for(File file:files){
					//method.addParameter(file.getName(), file);
					method.addParameter("content", file);
				}
				int status = mHttpClient.executeMethod(method);
				if(status==HttpStatus.SC_OK){
					response = convertResponse(method.getResponseBodyAsStream());
				}
			}
		}
		return response;
	}

上面的方法中使用的是

MultipartPostMethod,它自己本身是针对文件上传所做的,但是已经有点过时了,可用,推荐使用的是Post进行的文件上传

        /**
	 * 文件上传采用PostMethod
	 * @param url   服务器地址
	 * @param files  目标文件
	 * @notice 支持多文件上传
	 * @return JSON数据
	 * @throws Exception 
	 */
	public static String fileUploadPost(String url,List<File> files) throws Exception{
		String response = null;
		if(null != url && !"".equals(url)){
			if(null!=files && files.size()>0){
				mHttpClient = new HttpClient();
				mHttpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
				mHttpClient.getParams().setUriCharset("UTF-8");
				PostMethod postMethod = new PostMethod(url);				
				
				Part[] parts = new FilePart[files.size()];
				for(int i=0;i<files.size();i++){
					parts[i] = new FilePart(files.get(i).getName(), files.get(i).getAbsoluteFile());
				}				
				
				RequestEntity requestEntity = new MultipartRequestEntity(parts, postMethod.getParams());
				postMethod.setRequestEntity(requestEntity);
				int status = mHttpClient.executeMethod(postMethod);
				if(status==HttpStatus.SC_OK){
					response = convertResponse(postMethod.getResponseBodyAsStream());
				}
			}
		}
		return response;
	}

上面针对已经过时的方法做了改进!使用Post方式进行文件的上传



版权声明:本文为YaphetS_原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。