最近要做客户端上传图片和参数,服务器整合了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方法