android - 上传图片到服务器

标签 android upload

public class Upload {

ProgressDialog dialog = null;
int serverResponseCode = 0;
String uploadFilePath = null;
String uploadFileName = null;
String msg = null;
String upLoadServerUri = " http://192.168.1.179/index.php";
protected MainActivity context;

public Upload(MainActivity context) {
    this.context = context;
}

public int uploadFile(String sourceFileUri) {


    String fileName = sourceFileUri;

    HttpURLConnection conn = null;
    DataOutputStream dos = null;
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";
    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1 * 1024 * 1024;
    File sourceFile = new File(sourceFileUri);

    if (!sourceFile.isFile()) {

        context.dialog.dismiss();



        return 0;

    } else {
        try {

            // open a URL connection to the Servlet
            FileInputStream fileInputStream = new FileInputStream(sourceFile);
            URL url = new URL(upLoadServerUri);

            // Open a HTTP  connection to  the URL
            conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true); // Allow Inputs
            conn.setDoOutput(true); // Allow Outputs
            conn.setUseCaches(false); // Don't use a Cached Copy
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("ENCTYPE", "multipart/form-data");
            conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
            conn.setRequestProperty("uploaded_file", fileName);

            dos = new DataOutputStream(conn.getOutputStream());

            dos.writeBytes(twoHyphens + boundary + lineEnd);
            dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
                    + fileName + "\"" + lineEnd);

            dos.writeBytes(lineEnd);

            // 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);

            // Responses from the server (code and message)
            serverResponseCode = conn.getResponseCode();
            String serverResponseMessage = conn.getResponseMessage();

            Log.i("uploadFile", "HTTP Response is : "
                    + serverResponseMessage + ": " + serverResponseCode);

            if (serverResponseCode == 200) {


                InputStream is = conn.getInputStream();
                BufferedReader rd = new BufferedReader(new InputStreamReader(is));
                String line;
                StringBuffer response = new StringBuffer();
                while ((line = rd.readLine()) != null) {
                    response.append(line);
                    response.append('\r');
                }
                rd.close();
                context.q_no.setText(response);

                fileInputStream.close();
                dos.flush();
                dos.close();











                context.runOnUiThread(new Runnable() {
                    public void run() {

                        String msg = "yes";

                        //context.messageText.setText(msg);
                        Toast.makeText(context, "File Upload Complete.",
                                Toast.LENGTH_SHORT).show();
                    }
                });

            }
     } catch (MalformedURLException ex) {

     Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
        } catch (Exception e) {

            context.dialog.dismiss();
            e.printStackTrace();


            Log.e("Upload file to server Exception", "Exception : "
                    + e.getMessage(), e);
        }
        context.dialog.dismiss();
        return serverResponseCode;

     }
  }
}

我尝试了上面的代码来捕获图像并上传到 php 服务器。它工作正常。当我上传图像服务器时返回一个值。但是当我尝试这段代码时,我在图像上传到服务器和服务器响应后出现以下异常.

  07-27 10:50:55.303: W/System.err(4649):     android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

最佳答案

您在单独的线程(AsyncTask?)上正确运行 upload -- 很好。但是,无论何时与 UI 交互(.dialog.dismiss().setText(...) 等),您都需要在 UI 上运行它线程。

关于android - 上传图片到服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17894549/

相关文章:

java - 在android java中从XML填充ListView

android - 我的Android应用程序如何扫描自己的内存映射以查找已知的不良关键字,例如“Xposed”或“Frida”?

windows 7上的android开发和sql数据库

PHP上传多个文件只上传1个文件

c# - mvc c# 文件上传为字节数组

php - Move_uploaded_foto 到数据库

android - 如何在android中更改选项卡指示器文本的颜色?

android - 应用启动时收到奇怪的推送消息

jquery - 如何更新blueimp jquery文件上传以使用Bootstrap 4+

javascript - tinymce图片上传php插件什么的