【问题标题】:posting picture to php server将图片发布到 php 服务器
【发布时间】:2014-06-25 19:17:30
【问题描述】:

这是我在互联网上找到的将图片上传到服务器的方法。但它崩溃了。我不知道为什么。有人可以帮我解决这个问题吗?也许有人这样做了,并且知道更清晰的将照片上传到 php 服务器的示例?

private void doFileUpload() {
        HttpURLConnection conn = null;
        DataOutputStream dos = null;
        DataInputStream inStream = null;
        String exsistingFileName = "/mnt/sdcard/Pictures/album/test.jpg";

        // Is this the place are you doing something wrong.
        String lineEnd = "rn";
        String twoHyphens = "--";
        String boundary = "*****";

        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1 * 1024 * 1024;
        String responseFromServer = "";
        String urlString = "http://simplify.lt/android/debug";

        try {
            // ------------------ CLIENT REQUEST
            Log.e("MediaPlayer", "Inside second Method");
            FileInputStream fileInputStream = new FileInputStream(new File(
                    exsistingFileName));

            // open a URL connection to the Servlet
            URL url = new URL(urlString);

            // Open a HTTP connection to the URL
            conn = (HttpURLConnection) url.openConnection();

            // Allow Inputs
            conn.setDoInput(true);

            // Allow Outputs
            conn.setDoOutput(true);

            // Don't use a cached copy.
            conn.setUseCaches(false);

            // Use a post method.
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("Content-Type",
                    "multipart/form-data;boundary=" + boundary);

            dos = new DataOutputStream(conn.getOutputStream());
            dos.writeBytes(twoHyphens + boundary + lineEnd);
            dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\""
                    + exsistingFileName + "\"" + lineEnd);
            dos.writeBytes(lineEnd);
            Log.e("MediaPlayer", "Headers are written");

            // create a buffer of maximum size
            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);
            }

            // send multipart form data necesssary after file data...
            dos.writeBytes(lineEnd);
            dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

            // close streams
            Log.e("MediaPlayer", "File is written");
            fileInputStream.close();
            dos.flush();
            dos.close();

        }

        catch (MalformedURLException ex)

        {

            Log.e("MediaPlayer", "error: " + ex.getMessage(), ex);

        }

        catch (IOException ioe)

        {

            Log.e("MediaPlayer", "error: " + ioe.getMessage(), ioe);

        }

        // ------------------ read the SERVER RESPONSE
        try {
            inStream = new DataInputStream(conn.getInputStream());
            String str;

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

            inStream.close();
        }

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

    }

这里是日志:

05-08 14:51:09.609: E/AndroidRuntime(29477): FATAL EXCEPTION: main
05-08 14:51:09.609: E/AndroidRuntime(29477): Process: com.project.simplify, PID: 29477
05-08 14:51:09.609: E/AndroidRuntime(29477): android.os.NetworkOnMainThreadException
05-08 14:51:09.609: E/AndroidRuntime(29477):    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1145)
05-08 14:51:09.609: E/AndroidRuntime(29477):    at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
05-08 14:51:09.609: E/AndroidRuntime(29477):    at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
05-08 14:51:09.609: E/AndroidRuntime(29477):    at java.net.InetAddress.getAllByName(InetAddress.java:214)
05-08 14:51:09.609: E/AndroidRuntime(29477):    at com.android.okhttp.internal.Dns$1.getAllByName(Dns.java:28)
05-08 14:51:09.609: E/AndroidRuntime(29477):    at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:216)
05-08 14:51:09.609: E/AndroidRuntime(29477):    at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:122)
05-08 14:51:09.609: E/AndroidRuntime(29477):    at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:292)
05-08 14:51:09.609: E/AndroidRuntime(29477):    at com.android.okhttp.internal.http.HttpEngine.sendSocketRequest(HttpEngine.java:255)
05-08 14:51:09.609: E/AndroidRuntime(29477):    at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:206)
05-08 14:51:09.609: E/AndroidRuntime(29477):    at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:345)
05-08 14:51:09.609: E/AndroidRuntime(29477):    at com.android.okhttp.internal.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:89)
05-08 14:51:09.609: E/AndroidRuntime(29477):    at com.android.okhttp.internal.http.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:197)
05-08 14:51:09.609: E/AndroidRuntime(29477):    at com.project.simplify.StartedReviewsEditActivity.doFileUpload(StartedReviewsEditActivity.java:498)
05-08 14:51:09.609: E/AndroidRuntime(29477):    at com.project.simplify.StartedReviewsEditActivity.access$4(StartedReviewsEditActivity.java:454)
05-08 14:51:09.609: E/AndroidRuntime(29477):    at com.project.simplify.StartedReviewsEditActivity$2.onClick(StartedReviewsEditActivity.java:210)
05-08 14:51:09.609: E/AndroidRuntime(29477):    at android.view.View.performClick(View.java:4438)
05-08 14:51:09.609: E/AndroidRuntime(29477):    at android.view.View$PerformClick.run(View.java:18422)
05-08 14:51:09.609: E/AndroidRuntime(29477):    at android.os.Handler.handleCallback(Handler.java:733)
05-08 14:51:09.609: E/AndroidRuntime(29477):    at android.os.Handler.dispatchMessage(Handler.java:95)
05-08 14:51:09.609: E/AndroidRuntime(29477):    at android.os.Looper.loop(Looper.java:136)
05-08 14:51:09.609: E/AndroidRuntime(29477):    at android.app.ActivityThread.main(ActivityThread.java:5017)
05-08 14:51:09.609: E/AndroidRuntime(29477):    at java.lang.reflect.Method.invokeNative(Native Method)
05-08 14:51:09.609: E/AndroidRuntime(29477):    at java.lang.reflect.Method.invoke(Method.java:515)
05-08 14:51:09.609: E/AndroidRuntime(29477):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
05-08 14:51:09.609: E/AndroidRuntime(29477):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
05-08 14:51:09.609: E/AndroidRuntime(29477):    at dalvik.system.NativeStart.main(Native Method)

【问题讨论】:

  • 尝试从其他线程调用此方法,而不是从 UI 线程。
  • 什么线程?例如
  • 这段代码我取自stackoverflow.com/questions/4295417/…,没有使用线程
  • @user3416113 因为当时Android还允许在主线程上做网络。时光荏苒,Android 改变了对更新版本的政策。现在你必须使用ThreadAsyncTask。阅读here了解更多信息。

标签: android eclipse android-asynctask


【解决方案1】:

这不是在主线程上执行网络操作的正确方法 它抛出一个

android.os.NetworkOnMainThreadException

你最好创建一个新线程或者使用 AsyncTask 来实现,这样你就可以解决这个问题

你可以这样称呼它

  new Thread(new Runnable() {

        @Override
        public void run() {
            doFileUpload();
        }
    }).start();

注意:方法doFileUpload()中不应有任何UI操作;

【讨论】:

    猜你喜欢
    • 2011-11-18
    • 1970-01-01
    • 2020-08-08
    • 2022-06-12
    • 2011-07-21
    • 1970-01-01
    • 1970-01-01
    • 2020-11-25
    • 1970-01-01
    相关资源
    最近更新 更多