您的位置:首页 > 移动开发 > Android开发

Android上传文件到服务器(以山上传图片为例)

2015-05-27 15:39 288 查看
服务器端:

需要引入两个jar包:

commons-fileupload-1.2.2.jar

commons-io-2.0.1.jar

public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//doGet(request, response);
		
		//接收浏览器上传的文件
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		System.out.println(isMultipart);
		if(isMultipart){
			String realpath = request.getSession().getServletContext().getRealPath("/files");
			System.out.println(realpath);
			File dir = new File(realpath);
			if(!dir.exists()) dir.mkdirs();
			
			FileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(factory);
			upload.setHeaderEncoding("UTF-8");
			try {
				List<FileItem> items = upload.parseRequest(request);
				for(FileItem item : items){
					if(item.isFormField()){
						 String name1 = item.getFieldName();//因为上传文件的时候,可能携带其他的参数,这里得到请求参数的名称
						 String value = item.getString("UTF-8");//得到参数值
						 System.out.println(name1+ "="+ value);
					}else{
						item.write(new File(dir, System.currentTimeMillis()+ item.getName().substring(item.getName().lastIndexOf("."))));
					}
				}
				response.getOutputStream().write("上传成功".getBytes("utf-8"));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}else{
			doGet(request, response);
		}
	}


Android客户端:

需要引入3个jar包:

commons-codec-1.3.jar

commons-httpclient-3.1.jar

commons-logging-1.1.jar

<span style="white-space:pre">	</span>/**
	 * 发送文件到服务器,假设上传文件的时候携带其他的参数,这里携带两个参数:用户名和密码
	 * 
	 * @param path
	 *            服务器的路径
	 * @param filepath
	 *            本地文件的路径
	 */
	public static String sendFileByHttpPost(String path, String name,
			String pwd, String filepath) throws Exception {

		// 实例化上传数据的数据
		Part[] parts = { new StringPart("name", name),
				new StringPart("password", pwd),
				new FilePart("file", new File(filepath)) };
		
		PostMethod filePost=new PostMethod(path);
		
		filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
		//注意这里的HttpClient是commons包中的,而不是Android sdk中的
		org.apache.commons.httpclient.HttpClient client=new org.apache.commons.httpclient.HttpClient();
		client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
		int status=client.executeMethod(filePost);
		if(status==200){			
			return new String(filePost.getResponseBody());
		}else{
			throw new IllegalStateException("服务器状态异常");
		}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: