如何从Android上传图像到.net WebService

时间:2013-02-12 10:13:12

标签: android image-upload android-image

我正在尝试将图片上传到webService,但我无法做到这一点,我在这里和互联网上搜索了很多主题但却找不到好的解决方案。

当我运行此代码时,我收到错误请求错误。

更新:我使用了此链接中的一些代码:Uploading MS Word files from Android to .Net WCF?

但是给我FileNotFoundException,但我的文件路径是:/mnt/sdcard/ImageDir/images/ilan_1360917248037__thumb_.jpeg

这是我正在尝试的代码:

public static String imgUpload(String url, List<NameValuePair> list, List<String> images){

        String result = Constants.EMPTY;
        Bitmap bm;

        HttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, ServiceConstant.TIMEOUT_MILLISEC);
        HttpConnectionParams.setSoTimeout(httpParams, ServiceConstant.TIMEOUT_MILLISEC);

        HttpParams p = new BasicHttpParams();
        HttpClient httpclient = new DefaultHttpClient(p);


        HttpPost httppost = new HttpPost(url);        

        String resimYol = images.get(0);
        resimYol = resimYol.replace("file:///", "/");
        bm = BitmapFactory.decodeFile(resimYol);
        Log.d("RESIL_YOL", resimYol.toString());


        try{                        


            ByteArrayBody bab = new ByteArrayBody(b, resimYol);


            ResponseHandler<String> responseHandler = new BasicResponseHandler();  

            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            bm.compress(CompressFormat.JPEG, 100, bos);
            byte[] data = bos.toByteArray();            

            ByteArrayBody bab = new ByteArrayBody(data, resimYol);


            MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
            httppost.setEntity(reqEntity);    
        result = httpclient.execute(httppost,responseHandler);

        }

        catch (Exception e) {
              // handle exception here
              Log.e(e.getClass().getName(), e.getMessage());
            }
        return result; 
    }

这是我的logcat:

02-12 11:43:07.467: E/org.apache.http.client.HttpResponseException(19112): Bad Request

3 个答案:

答案 0 :(得分:0)

试试这个例子Link它可能对你有帮助。

并添加所需的所有jar文件。

答案 1 :(得分:0)

尝试转换image中的Base64,然后将其String响应作为参数发送到Web服务,以便成功上传到服务器。

答案 2 :(得分:0)

public static String __imgUpload(String url, List<NameValuePair> list, List<String> images)
    {
         URL url1=null;
         HttpURLConnection conn = null;
         DataOutputStream dos = null;
         DataInputStream inStream = null;
         String existingFileName= null;

            String urlServer = url;
            String lineEnd = "\r\n";
            String twoHyphens = "--";
            String boundary =  "*****"; 
            String str = null;

         int bytesRead, bytesAvailable, bufferSize;
         byte[] buffer;
         int maxBufferSize = Integer.MAX_VALUE;
         String responseFromServer = "";


          try {
            url1 = new URL(url);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }                

          for(int resimID=0;resimID<images.size();resimID++)
          {
             existingFileName=    images.get(resimID); 
             existingFileName = existingFileName.replace("file:///", "/");

             try
             {
             FileInputStream fileInputStream = new FileInputStream(new File(existingFileName) );


              conn = (HttpURLConnection) url1.openConnection();

              conn.setDoInput(true);

              conn.setDoOutput(true);

              conn.setUseCaches(false);

              conn.setRequestMethod("POST");
              conn.setRequestProperty("Connection", "Keep-Alive");
              conn.setRequestProperty("Content-Type", "application/stream");
              dos = new DataOutputStream( conn.getOutputStream() );

              bytesAvailable = fileInputStream.available();
              bufferSize = Math.min(bytesAvailable, maxBufferSize);
              buffer = new byte[bufferSize];
              // read file and write it into form...
              bytesRead = fileInputStream.read(buffer, 0, bufferSize);
              while (bytesRead > 0)
              {
               dos.write(buffer, 0, bufferSize);
               bytesAvailable = fileInputStream.available();
               bufferSize = Math.min(bytesAvailable, maxBufferSize);
               bytesRead = fileInputStream.read(buffer, 0, bufferSize);

              }

              dos.writeBytes(lineEnd);


              // close streams
              Log.e("Debug",twoHyphens + boundary + twoHyphens + lineEnd);
              fileInputStream.close();
              dos.flush();
              dos.close();
             }
             catch (MalformedURLException ex)
             {
                  Log.e("Debug", "error 1: " + ex.getMessage(), ex);
             }
             catch (IOException ioe)
             {
                  Log.e("Debug", "error 2: " + ioe.getMessage(), ioe);
             }

             try {
                   inStream = new DataInputStream ( conn.getInputStream() );


                   while (( str = inStream.readLine()) != null)
                   {
                        Log.e("Debug","Server Response "+str);
                   }
                   inStream.close();

             }
             catch (IOException ioex){
                  Log.e("Debug", "error 3: " + ioex.getMessage(), ioex);
             }  
          }

             return str;
    }

这段代码肯定有用。