java 文件上传

来源:互联网 发布:意外的sql命令结尾 编辑:程序博客网 时间:2024/05/21 15:47

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

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
原创粉丝点击