Android上传图片到服务器
上传图片到服务器首先要在SD卡上生成一个图片。 Java代码复制内容到剪贴板 Stringpath=Environment.getDataDirectory().getPath()+"/data/"+ getPackageName()+"/"+"upload.jpg"; Filefile=newFile(path); ByteArrayOutputStreambaos=newByteArrayOutputStream(); bitMap.compress(Bitmap.CompressFormat.PNG,85,baos);//bitMap是要上传的图片Bitmap byte[]photoBytes=baos.toByteArray(); if(!file.exists()) file.createNewFile(); FileOutputStreamfos=newFileOutputStream(file); fos.write(photoBytes); fos.flush(); fos.close(); 然后再调用下面的方法: Java代码复制内容到剪贴板 /** *上传文件和文字 *@paramaFile *@paramstatus *@paramurlPath *@return */ publicbooleanuploadStatus(FileaFile,Stringstatus,StringurlPath){ booleanresult=false; try{ URLurl=newURL(urlPath); HttpURLConnectionrequest=(HttpURLConnection)url .openConnection(); request.setDoOutput(true); request.setRequestMethod("POST"); Stringboundary="---------------------------37531613912423"; Stringcontent="--" +boundary +"\r\nContent-Disposition:form-data;name=\"status\"\r\n\r\n"; Stringpic="\r\n--" +boundary +"\r\nContent-Disposition:form-data;name=\"pic\";"+ "filename=\"image.jpg\"\r\nContent-Type:image/jpeg\r\n\r\n"; byte[]end_data=("\r\n--"+boundary+"--\r\n").getBytes(); FileInputStreamstream=newFileInputStream(aFile); byte[]file=newbyte[(int)aFile.length()]; stream.read(file); request.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);//设置表单类型和分隔符 request.setRequestProperty( "Content-Length", String.valueOf(content.getBytes().length +status.getBytes().length+pic.getBytes().length +aFile.length()+end_data.length));//设置内容长度 OutputStreamot=request.getOutputStream(); ot.write(content.getBytes()); ot.write(status.getBytes()); ot.write(pic.getBytes()); ot.write(file); ot.write(end_data); ot.flush(); ot.close(); request.connect(); if(200==request.getResponseCode()){ result=true; }else{ result=false; } }catch(FileNotFoundExceptione1){ e1.printStackTrace(); }catch(IOExceptione){ e.printStackTrace(); } returnresult; } 本文转自06peng 51CTO博客,原文链接:http://blog.51cto.com/06peng/962490,如需转载请自行联系原作者