将图像上传到服务器

时间:2012-10-17 10:21:13

标签: android

将图片上传到服务器的代码: 这里的全文代码

static{
    httpclient=new DefaultHttpClient();
    httpPost=new HttpPost(serverUrl);
}

public String uploadImage(String imageFileURL){

    Bitmap bitmap=BitmapFactory.decodeFile(imageFileURL);
    ByteArrayOutputStream baos=new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 90, baos);
    byte []ba=baos.toByteArray();
    String bal=Base64.encodeBytes(ba);
    ArrayList<NameValuePair> nameValuePair=new ArrayList<NameValuePair>();
    nameValuePair.add(new BasicNameValuePair("image",bal));
     String res = "";
     StringBuffer buffer = new StringBuffer();
    try {
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
        httpresponse=httpclient.execute(httpPost);
        httpEntity=httpresponse.getEntity();
        inputStream=httpresponse.getEntity().getContent();

        int contentLength=(int) httpresponse.getEntity().getContentLength();
        if(contentLength<0){

        }
        else{
            byte []data =new byte[512];
            int len=0;
            try{
                while(-1 !=(len=inputStream.read(data))){
                    buffer.append(new String(data,0,len));
                }

            }
            catch(IOException e){
                e.printStackTrace();
                return null;
            }
        }

    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    finally{
        try {
            inputStream.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    res=buffer.toString();
    return res; 
}

上调用此方法
 onClick(View view){
    new Thread(new Runnable(){

        public void run() {
            // TODO Auto-generated method stub
            response=new ServerCommunication().uploadImage(path);
        }           
    }).start();

但它显示为TimeOutException。任何人都能说出我做错了什么。

1 个答案:

答案 0 :(得分:0)

添加此代码以删除超时异常:

final int TIMEOUT_MILLISEC = 20000;
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams,TIMEOUT_MILLISEC);
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);