java 文件上传

话不多说,说多了都是泪----直接上源代码

public String postPicture(ArrayList<ImageItem> images){
String s=new String();
Log.e("imagessss",images.size()+"");
String end = "\r\n";  
String twoHyphens = "--";  
String boundary = "--------httppost123"; 
String url = getUrl(ApiConstants.API_POST_PICUTRE) ;
List<Cookie> cookies = BaseHttpTransfer.getCookie(mContext).getCookies();
try {
HttpURLConnection conn=(HttpURLConnection) new URL(url).openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
// conn.setRequestProperty("charset", "utf-8");//charset=utf-8;
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive"); 
conn.setRequestProperty("Cookie", toString(cookies.get(0))+";fileListStyle=file-list; language=zh_CN;"+toString(cookies.get(2)));
DataOutputStream ds =  
new DataOutputStream(conn.getOutputStream()); 
for(ImageItem i:images){
Log.e("imagessss",images.indexOf(i)+"");
ByteArrayOutputStream baos = new ByteArrayOutputStream();    
i.getBitmap().compress(Bitmap.CompressFormat.PNG, 100, baos);    
String filename =i.getImagePath().substring(1);  
Log.e("filename",filename);
ds.write((twoHyphens + boundary + end).getBytes());  
ds.write(("Content-Disposition: form-data; " +  "name=\""+"file"+ images.indexOf(i)+"\"" +
";filename=\"" +   URLEncoder.encode(filename, "UTF-8")+"\""+
end).getBytes());  
    ds.write(("Content-Type: " + "image/jpg" + "\r\n\r\n").getBytes());
Log.e("baos.to",baos.toByteArray().toString());
ds.write(baos.toByteArray());
ds.write(end.getBytes());  
}
ds.write((twoHyphens + boundary + twoHyphens + end).getBytes());  
ds.flush(); 
ds.close(); 
// conn.connect();
Log.e("返回值",conn.getResponseCode()+"");
if(conn.getResponseCode()==200){
Log.e("我的图片偏","成功");
}else{
Log.e("我的图片偏","budui");
}
InputStream is = conn.getInputStream(); 
int ch;  
StringBuffer b = new StringBuffer();  
while ((ch = is.read()) != -1) {  
b.append((char) ch);  
}  
s = b.toString();  
Log.e("返回来的数据",s);
try{
CommonMessageInterface objResult = mGson.fromJson(s, CommonMessageInterface.class);
if(objResult.getCode() == Constants.REQUEST_SUCCESS_CODE_INT_FIRST){
return s;
}else{
return "";
}
}catch(Exception e){
return "";
}


} catch (Exception e) {  
return "";
}  

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值