1.使用HttpClient进行上传,Enity里面可以包含文件对象;
2.可以把图片编成Base64字符串,发送到服务器(之个适合图片较小的);
/**
* 把图片编成Base64字符串
* imageUrl 图片路径
*/
public String getImageStr(String imageUrl) throws Exception{
byte[] data=null;
FileInputStream in=new FileInputStream(imageUrl);
data=new byte[in.available()];
ByteArrayOutputStream os=new ByteArrayOutputStream();
int len=0;
while((len=in.read(data))!=-1){
os.write(data, 0, len);
};
data=os.toByteArray();
os.close();
in.close();
return Base64.encodeToString(data, Base64.DEFAULT);
}
3.可以转为二进制然后传到服务器
* 照片转byte二进制
* @param imagepath 需要转byte的照片路径
* @return 已经转成的byte
* @throws Exception
*/
public static byte[] readStream(String imagepath) throws Exception {
FileInputStream fs = new FileInputStream(imagepath);
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while (-1 != (len = fs.read(buffer))) {
outStream.write(buffer, 0, len);
}
outStream.close();
fs.close();
return outStream.toByteArray();
}
4.通过表单文件方式上传
/* 上传文件至Server的方法 */ privatevoid uploadFile(String imageUrl) { String end ="\r\n"; String twoHyphens ="--"; String boundary ="*****"; try { URL url =new URL(imageUrl); HttpURLConnection con=(HttpURLConnection)url.openConnection(); /* 允许Input、Output,不使用Cache */ con.setDoInput(true); con.setDoOutput(true); con.setUseCaches(false); /* 设置传送的method=POST */ con.setRequestMethod("POST"); /* setRequestProperty */ con.setRequestProperty("Connection", "Keep-Alive"); con.setRequestProperty("Charset", "UTF-8"); con.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary); /* 设置DataOutputStream */ DataOutputStream ds = new DataOutputStream(con.getOutputStream()); ds.writeBytes(twoHyphens + boundary + end); ds.writeBytes("Content-Disposition: form-data; "+ "name=\"file1\";filename=\""+ newName +"\""+ end); ds.writeBytes(end); /* 取得文件的FileInputStream */ FileInputStream fStream =new FileInputStream(imageUrl); byte[] buffer =newbyte[1024]; int length =0; /* 从文件读取数据至缓冲区 */ while((length = fStream.read(buffer)) !=-1) { /* 将资料写入DataOutputStream中 */ ds.write(buffer, 0, length); } ds.writeBytes(end); ds.writeBytes(twoHyphens + boundary + twoHyphens + end); /* close streams */ fStream.close(); ds.flush(); /* 取得Response内容 */ InputStream is = con.getInputStream(); int ch; StringBuffer b =new StringBuffer(); while( ( ch = is.read() ) !=-1 ) { b.append( (char)ch ); } /* 将Response显示于Dialog */ Log.i("cy","上传成功"+b.toString().trim()); /* 关闭DataOutputStream */ ds.close(); } catch(Exception e) { Log.i("cy","上传失败"+e); } }
1万+

被折叠的 条评论
为什么被折叠?



