将图像从android上传到服务器php时出错?

Posted

技术标签:

【中文标题】将图像从android上传到服务器php时出错?【英文标题】:Error when upload image from android to server php? 【发布时间】:2012-11-15 02:06:22 【问题描述】:

我想将图像从 android 设备上传到服务器 php,但我的应用程序出错。你能帮我修一下吗?谢谢! 源代码

public class MainActivity extends Activity implements OnClickListener 

private ImageView image;
private Button btnselect;
private Button btnupload;
private Bitmap bmp;
private HttpResponse response;



@Override
public void onCreate(Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    image = (ImageView) findViewById(R.id.image);
    btnselect = (Button) findViewById(R.id.btnselect);
    btnupload = (Button) findViewById(R.id.btnupload);
    btnselect.setOnClickListener(this);
    btnupload.setOnClickListener(this);
    Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(),
            R.drawable.electricinvoicesign);
    image.setImageBitmap(bitmapOrg);


@Override
public void onClick(View v) 
    // TODO Auto-generated method stub
    switch (v.getId()) 
    case R.id.btnselect:
        Intent choosePictureIntent = new Intent(
                Intent.ACTION_PICK,
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(choosePictureIntent, 0);
        break;
    case R.id.btnupload:
        new upload().execute();
        break;
    default:
        break;
    


public void hienthi()

    Toast.makeText(this, "Upload thanh cong!", Toast.LENGTH_LONG).show();


private class upload extends AsyncTask<Void, Void, Void>


    private ProgressDialog progressDialog;
    private BufferedReader in;


    @Override
    protected void onPostExecute(final Void unused) 
        try
        
        this.progressDialog.dismiss();
        System.out.print("Upload thanh cong!");
        hienthi();
        in = new BufferedReader(new InputStreamReader(response
                .getEntity().getContent()));
        StringBuffer sb = new StringBuffer("");
        String line = "";
        String NL = System.getProperty("line.separator");
        while ((line = in.readLine()) != null) 
            sb.append(line + NL);
        
        in.close();
        String result = sb.toString();
        System.out.println(result);
        catch(Exception e)
        
            e.printStackTrace();
        
    

    @Override
    protected void onPreExecute() 
        this.progressDialog = ProgressDialog.show(
                MainActivity.this, "", " Loading...");
    

    @Override
    protected Void doInBackground(Void... params) 
        // TODO Auto-generated method stub
        try 
            Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(),
                    R.drawable.electricinvoicesign);
            ByteArrayOutputStream bao = new ByteArrayOutputStream();
            bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, bao);
            byte[] ba = bao.toByteArray();
            String ba1 = Base64.encodeBytes(ba);
            ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("image", ba1));
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(
                        "http://longvansolution.tk/uploadimage.php");
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            response=httpclient.execute(httppost);
            System.out.print("Upload thanh cong 2!");

         catch (Exception e) 
            Log.e("log_tag", "Error in http connection " + e.toString());
        

        return null;
    



@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) 
    // TODO Auto-generated method stub
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK) 
        Uri imageFileUri = data.getData();
        try 
            BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
            bmpFactoryOptions.inJustDecodeBounds = true;
            bmp = BitmapFactory
                    .decodeStream(
                            getContentResolver().openInputStream(
                                    imageFileUri), null, bmpFactoryOptions);
            bmpFactoryOptions.inJustDecodeBounds = false;
            bmp = BitmapFactory
                    .decodeStream(
                            getContentResolver().openInputStream(
                                    imageFileUri), null, bmpFactoryOptions);
            image.setImageBitmap(bmp);
         catch (Exception e) 
            Log.v("ERROR", e.toString());
        
    

这是错误:

11-15 13:59:04.642: W/System.err(17525): android.os.NetworkOnMainThreadException 11-15 13:59:04.642: W/System.err(17525): 在 android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099) 11-15 13:59:04.642: W/System.err(17525): 在 libcore.io.BlockGuardOs.recvfrom(BlockGuardOs.java:163) 11-15 13:59:04.642: W/System.err(17525): 在 libcore.io.IoBridge.recvfrom(IoBridge.java:503) 11-15 13:59:04.642: W/System.err(17525): 在 java.net.PlainSocketImpl.read(PlainSocketImpl.java:488) 11-15 13:59:04.642: W/System.err(17525): 在 java.net.PlainSocketImpl.access$000(PlainSocketImpl.java:46) 11-15 13:59:04.642: W/System.err(17525): 在 java.net.PlainSocketImpl$PlainSocketInputStream.read(PlainSocketImpl.java:240) 11-15 13:59:04.642: W/System.err(17525): 在 org.apache.http.impl.io.AbstractSessionInputBuffer.fillBuffer(AbstractSessionInputBuffer.java:103) 11-15 13:59:04.642: W/System.err(17525): 在 org.apache.http.impl.io.AbstractSessionInputBuffer.read(AbstractSessionInputBuffer.java:134) 11-15 13:59:04.642: W/System.err(17525): 在 org.apache.http.impl.io.ChunkedInputStream.read(ChunkedInputStream.java:161) 11-15 13:59:04.642: W/System.err(17525): 在 org.apache.http.conn.EofSensorInputStream.read(EofSensorInputStream.java:159) 11-15 13:59:04.642: W/System.err(17525): 在 java.io.InputStreamReader.read(InputStreamReader.java:244) 11-15 13:59:04.642: W/System.err(17525): 在 java.io.BufferedReader.fillBuf(BufferedReader.java:130) 11-15 13:59:04.642: W/System.err(17525): 在 java.io.BufferedReader.readLine(BufferedReader.java:390) 11-15 13:59:04.642: W/System.err(17525): 在 com.example.uploadimage.MainActivity$upload.onPostExecute(MainActivity.java:99) 11-15 13:59:04.642: W/System.err(17525): 在 com.example.uploadimage.MainActivity$upload.onPostExecute(MainActivity.java:1) 11-15 13:59:04.642: W/System.err(17525): 在 android.os.AsyncTask.finish(AsyncTask.java:602) 11-15 13:59:04.642: W/System.err(17525): 在 android.os.AsyncTask.access$600(AsyncTask.java:156) 11-15 13:59:04.642: W/System.err(17525): 在 android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:615) 11-15 13:59:04.642: W/System.err(17525): 在 android.os.Handler.dispatchMessage(Handler.java:99) 11-15 13:59:04.642: W/System.err(17525): 在 android.os.Looper.loop(Looper.java:137) 11-15 13:59:04.642: W/System.err(17525): 在 android.app.ActivityThread.main(ActivityThread.java:4514) 11-15 13:59:04.642: W/System.err(17525): 在 java.lang.reflect.Method.invokeNative(Native Method) 11-15 13:59:04.650: W/System.err(17525): 在 java.lang.reflect.Method.invoke(Method.java:511) 11-15 13:59:04.650: W/System.err(17525): 在 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:790) 11-15 13:59:04.650: W/System.err(17525): 在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557) 11-15 13:59:04.650: W/System.err(17525): at dalvik.system.NativeStart.main(Native Method)

【问题讨论】:

学习阅读logcat 11-15 08:49:26.820: E/AndroidRuntime(4199): java.lang.ClassCastException: org.apache.http.conn.EofSensorInputStream cannot be cast to com.example.uploadimage.Base64$InputStream 11-15 08:49:26.820: E/AndroidRuntime(4199): at com.example.uploadimage.MainActivity$upload.onPostExecute(MainActivity.java:80)。检查 MainActivity 中的第 80 行。你选错了课程。 【参考方案1】:

我相信您导入了错误的InputStream 类。 好像你在你的应用程序的某个地方定义了一个InputStream 类或其他东西,使用来自java.io 的那个。

【讨论】:

我从drawable中取出文件并上传到服务器,我的服务器得到图像,结果正常。但几秒钟后,服务器上的图像返回大小为零。如果我上传文件txt,这个文件txt 永远,直到我删除它。我不明白为什么?

以上是关于将图像从android上传到服务器php时出错?的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 asynctask 将图像从 android 上传到 php

从android应用程序上传多个图像文件到php服务器

尝试使用 js、jquery 和 PHP 上传图片时出错

错误的未定义索引将图像上传到服务器

尝试将图像上传到 Firebase 存储时出错

尝试从 php FORM 上传到 MYSQL 数据库时出错