Java 将图像从android手机上传到服务器

Java 将图像从android手机上传到服务器,java,android,image-uploading,Java,Android,Image Uploading,我是android新手,尝试将图像上传到服务器。 从网上得到了一些示例代码。但是它显示了一些我无法处理的错误。有人能帮我吗。获取代码的链接是 错误是越来越严重 “类型Base64的方法encodeBytes(字节[])未定义” 以及相应的 我甚至在项目中下载了base64.java文件中没有encodeBytes。使用。Whaaa 你必须缩进你的代码 对于每一个{打开,您都应该在右边留出一个空格,以便更好地看到您的代码在做什么: 这很好: try { so

我是android新手,尝试将图像上传到服务器。 从网上得到了一些示例代码。但是它显示了一些我无法处理的错误。有人能帮我吗。获取代码的链接是

错误是越来越严重

“类型Base64的方法encodeBytes(字节[])未定义”

以及相应的


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

中没有
encodeBytes
。使用。

Whaaa

你必须缩进你的代码

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

这很好:

        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
以缩进


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

您只需将文件作为ByTestStream打开,并将其作为流发送到您的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();

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

您可以使用这些方法

public static String encodeToString (byte[] input, int offset, int len, int flags)
自:API 8级

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

参数

输入:要编码的数据

偏移量:输入数组中开始的位置

len:要编码的输入字节数

标志:控制编码输出的某些功能

传递默认值将导致符合RFC 2045的输出

public static String encodeToString (byte[] input, int flags)
自:API 8级

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

参数

输入:要编码的数据

标志:控制编码输出的某些功能。

传递默认值将导致符合RFC 2045的输出。

公共类UploadImage extends活动{
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;
输入流输入流; @凌驾 创建公共空间(捆绑冰柱){ 超级冰柱; setContentView(R.layout.main); 位图Bitmap=BitmapFactory.decodeResource(getResources(),R.drawable.icon);ByteArrayOutputStream=new ByteArrayOutputStream(); compress(bitmap.CompressFormat.PNG,90,stream);//压缩为所需格式。 byte[]byte_arr=stream.toByteArray(); 字符串image\u str=Base64.encodeBytes(byte\u arr); ArrayList nameValuePairs=新的ArrayList(); 添加(新的BasicNameValuePair(“image”,image_str)); 试一试{ HttpClient HttpClient=新的DefaultHttpClient(); HttpPost HttpPost=新的HttpPost(“http://10.0.2.2/Upload_image_ANDROID/upload_image.php"); setEntity(新的UrlEncodedFormEntity(nameValuePairs)); HttpResponse response=httpclient.execute(httppost); 字符串\u字符串\u响应=convertResponseToString(响应); Toast.makeText(UploadImage.this,“Response”+字符串响应Toast.LENGTH.LONG.show(); }捕获(例外e){ Toast.makeText(UploadImage.this,“ERROR”+e.getMessage(),Toast.LENGTH\u LONG.show(); System.out.println(“http连接中的错误”+e.toString()); } } 公共字符串convertResponseToString(HttpResponse响应)引发IllegalStateException,IOException{ 字符串res=“”; StringBuffer=新的StringBuffer(); inputStream=response.getEntity().getContent(); int contentLength=(int)response.getEntity().getContentLength();//获取内容长度…。。 Toast.makeText(UploadImage.this,“contentLength:+contentLength,Toast.LENGTH_LONG).show(); if(contentLength<0){ } 否则{ 字节[]数据=新字节[512]; int len=0; 尝试 { 而(-1!=(len=inputStream.read(data))) { append(新字符串(数据,0,len));//转换为字符串并追加到stringbuffer…。。 } } 捕获(IOE异常) { e、 printStackTrace(); } 尝试 { inputStream.close();//关闭流…。。 } 捕获(IOE异常) { e、 printStackTrace(); } res=buffer.toString();//正在将stringbuffer转换为字符串…。。 Toast.makeText(UploadImage.this,“结果:+res,Toast.LENGTH_LONG).show(); //System.out.println(“Response=>”+EntityUtils.toString(Response.getEntity()); } 返回res;
感谢您发布答案!虽然代码片段可以回答这个问题,但添加一些附加信息(如解释等)仍然很好。。