关于httpClient上传文件

本文详细介绍了一种使用Java客户端通过HTTP Post方式上传图片及参数至服务器的方法。具体包括使用MultipartEntity构建请求体,处理SessionID,以及服务器端接收并处理上传文件的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


    最近要做客户端上传图片和参数,服务器整合了SSH . 废话不多说,上代码


客户端:

      

import java.io.File;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.CookieStore;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;

public class Test(){
    
        //photoFileName
	public void upload() throws Exception{
		
		String url = "http://localhost:8080/scan/mperson_upLoadImage.action";
		
		HashMap<String, Object>params =new HashMap<String, Object>();
		
		params.put("id", 3);
		
		
		
		String imagepath = "C:/Users/zsq/Desktop/abc.png";
		
		  MultipartEntity mpEntity = new MultipartEntity(); 

	        if (params != null && !params.isEmpty()) { 

	            for (Map.Entry<String, Object> entry : params.entrySet()) { 

	 
                     //参数名
	                StringBody par = new StringBody(entry.getValue().toString()); 
   
	                mpEntity.addPart(entry.getKey(), par); 

	            } 

	        } 
	    
	        // 图片 

	        if (!imagepath.equals("")) { 

	            FileBody file = new FileBody(new File(imagepath)); 

	            mpEntity.addPart("photo", file); 

	        } 

	        // 使用HttpPost对象设置发送的URL路径 

	        HttpPost post = new HttpPost(url); 
	        post.setHeader("Cookie", "JSESSIONID=" + JSESSIONID);
	        // 发送请求体 

	        post.setEntity(mpEntity); 

	        // 创建一个浏览器对象,以把POST对象向服务器发送,并返回响应消息 

	        DefaultHttpClient client = new DefaultHttpClient(); 

	        HttpResponse response = client.execute(post);
	        

			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				// 封装了服务器端返回的数据
				HttpEntity responseEntity = response.getEntity();
				// 将服务器返回的输入流 解析为 字符串
				// EntityUtils.toString(responseEntity)
				
				//对服务器返回的session进行记录
				  CookieStore mCookieStore = ((DefaultHttpClient) client).getCookieStore();
				
				  List<Cookie> cookies = mCookieStore.getCookies();
				  
				  for (int i = 0; i < cookies.size(); i++) {
					  //如果cookies头和"JSESSIONID" 就记录sessionID
					  if("JSESSIONID".equals(cookies.get(i).getName())){
						  JSESSIONID = cookies.get(i).getValue();
						  break;
					  }
					
				}
				InputStream is =  responseEntity.getContent();
				
			String result = StreamUtils.read(is);
			System.out.println("上传的结果是 : "+ result);
			       	  
			}
		
		
	}
	

}

工具类StreamUtils.java(只是将流转成字符串):


import java.io.ByteArrayOutputStream;
import java.io.InputStream;

public class StreamUtils {

	public static String read(InputStream is) throws Exception {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		
		byte[] buf = new byte[1024];
		int len = -1;
		
		while ( (len = is.read(buf)) != -1 ) {
			baos.write(buf, 0, len);
		}
		
		baos.close();
		is.close();
		
		return new String(baos.toByteArray());
	}

}


uploadFileName  // 是strust2 自动把上传文件的名字封装到这个uploadFileName





javaWeb端

String String photoName;
public  void  upLoadImage () throws Exception{
		
		System.out.println("有到upLoadImage这里来?");
		String realPath = ServletActionContext.getServletContext().getRealPath("/WEB-INF/person_photo");
		System.out.println(realPath);
		System.out.println("uploadFileName : "+photoFileName);
		UUID uuid = UUID.randomUUID();
       
		int id = model.getId();
		System.out.println("得到的ID: "+model.getId());
		//System.out.println("photoContentType"+v);
		
		String fileLastName = photoFileName.substring(photoFileName.lastIndexOf("."));
		
		//存放的是UUID的名字
		String uuidName = uuid.toString()+fileLastName;
		PrintWriter writer = getWriter();
		if(photo!=null){
			File saveFile = new File(new File(realPath),uuidName);
			FileUtils.copyFile(photo, saveFile);
			writer.print("{scuess:true}");
		}else{
			
			writer.print("{scuess:false,error:'photo_null'}");
		}
		    
	
	
	  
	}

    public String getPhotoFileName() {
        return photoFileName;
    }

    public void setPhotoFileName(String photoFileName) {
        this.photoFileName = photoFileName;
    }




photoFileName  strus2自动将文件名封装到photoFileName,你的jsp例如:<input name="xxx"
type="file"/> 这是就是用xxxFileName。 还有一个xxxFileType。获取文件的类型。
注意:必须给 xxxFileName和xxxFileType提供get,set方法


    


  

    

转载于:https://my.oschina.net/janson2013/blog/124487

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值