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

服务器端:

需要引入两个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("服务器状态异常");
		}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值