【问题标题】:upload image from android phone to the server从安卓手机上传图片到服务器
【发布时间】:2011-11-16 18:52:56
【问题描述】:

我是 android 新手,试图将图像上传到服务器。 从网上得到了一些示例代码。但它在无法处理的行中显示了一些错误。在这种情况下,任何人都可以帮助我。获取代码的链接是http://blog.sptechnolab.com/2011/03/09/android/android-upload-image-to-server/

错误是

“方法 encodeBytes(byte[]) 未定义 Base64 类型”

以及对应的

我什至在项目中下载了base64.java文件

【问题讨论】:

    标签: java android image-uploading


    【解决方案1】:

    API 中没有 encodeBytes。使用encodeToString

    【讨论】:

      【解决方案2】:

      哇!

      必须indent你的代码!

      对于您打开的每个 {,您应该向右留出空格,以便您可以更好地看到您的代码在做什么:

      这很好:

              try {
                  something();
              } catch (Exception e) {
                  weMessedUp();
                  if (e == i)
                  {
                      lol();
                  }
              }
      

      这很糟糕:

              try {
              something();
              } catch (Exception e) {
              weMessedUp();
              if (e == i)
              {
              lol();
              }
              }
      

      仅供阅读,如果在一周内你想修改一些东西,你的程序会更快理解。

      在 Eclipse 中缩进,ctrl + a 选择整个代码,然后ctrl + i 缩进。

      这不会回答您的问题,但会帮助其他人回答并提高您的技能。

      【讨论】:

        【解决方案3】:

        您可以简单地将文件作为字节流打开并将其作为流发送到您的 httpconnection?

        像这样以流的形式打开文件:

          File inFile = new File(fileName);
          BufferedReader br = new BufferedReader(
                                   new InputStreamReader(
                                        new FileInputStream(inFile)
                                   )
                              );
        
           URL url = new URL("http://www.google.com");
           URLConnection connection = url.openConnection();
           connection.setDoOutput(true);
           OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
           while ((decodedString = br.readLine()) != null) {
               out.write(decodedString);
            }
            out.close();
        

        这是逐行读取文件的实现。不确定它是否会在没有换行符的情况下对图像进行编码,但您应该能够重新设计以逐字节流式传输而不会遇到太多麻烦。

        【讨论】:

          【解决方案4】:

          您可以改用这些方法

          public static String encodeToString (byte[] input, int offset, int len, int flags)
          

          自:API 级别 8

          Base64 编码给定数据并返回一个新分配的字符串和结果。

          参数

          输入:要编码的数据

          offset : 输入数组中开始的位置

          len : 要编码的输入字节数

          flags :控制编码输出的某些特征。

          传递 DEFAULT 会导致输出符合 RFC 2045。

          public static String encodeToString (byte[] input, int flags)
          

          自:API 级别 8

          Base64 编码给定数据并返回一个新分配的字符串和结果。

          参数

          输入:要编码的数据

          标志:控制编码输出的某些特征。

          传递 DEFAULT 会导致输出符合 RFC 2045。

          【讨论】:

            【解决方案5】:
            public class UploadImage extends Activity {
            InputStream inputStream;
                @Override
            public void onCreate(Bundle icicle) {
                    super.onCreate(icicle);
                    setContentView(R.layout.main);
            
                    Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.icon);           ByteArrayOutputStream <span id="IL_AD5" class="IL_AD">stream</span> = new ByteArrayOutputStream();
                    bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream); //compress to which format you want.
                    byte [] byte_arr = stream.toByteArray();
                    String image_str = Base64.encodeBytes(byte_arr);
                    ArrayList<NameValuePair> nameValuePairs = new  ArrayList<NameValuePair>();
            
                    nameValuePairs.add(new BasicNameValuePair("image",image_str));
            
                    try{
                        HttpClient httpclient = new DefaultHttpClient();
                        HttpPost httppost = new HttpPost("http://10.0.2.2/Upload_image_ANDROID/upload_image.php");
                        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                        HttpResponse response = httpclient.execute(httppost);
                        String the_string_response = convertResponseToString(response);
                        Toast.makeText(UploadImage.this, "Response " + the_string_response, Toast.LENGTH_LONG).show();
                    }catch(Exception e){
                          Toast.makeText(UploadImage.this, "ERROR " + e.getMessage(), Toast.LENGTH_LONG).show();
                          System.out.println("Error in http connection "+e.toString());
                    }
                }
            
                public String convertResponseToString(HttpResponse response) throws IllegalStateException, IOException{
            
                     String res = "";
                     StringBuffer buffer = new StringBuffer();
                     inputStream = response.getEntity().getContent();
                     int contentLength = (int) response.getEntity().getContentLength(); //getting content length…..
                     Toast.makeText(UploadImage.this, "contentLength : " + contentLength, Toast.LENGTH_LONG).show();
                     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)); //converting to string and appending  to stringbuffer…..
                                }
                            }
                            catch (IOException e)
                            {
                                e.printStackTrace();
                            }
                            try
                            {
                                inputStream.close(); // closing the stream…..
                            }
                            catch (IOException e)
                            {
                                e.printStackTrace();
                            }
                            res = buffer.toString();     // converting stringbuffer to string…..
            
                            Toast.makeText(UploadImage.this, "Result : " + res, Toast.LENGTH_LONG).show();
                            //System.out.println("Response => " +  EntityUtils.toString(response.getEntity()));
                     }
                     return res;
            

            【讨论】:

            • 感谢您发布答案!虽然代码 sn-p 可以回答这个问题,但添加一些附加信息仍然很棒,比如解释等..
            猜你喜欢
            • 2012-07-21
            • 2011-09-18
            • 2021-12-13
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多