图片上传到服务器图片上传、服务器

由网友(风云谁人盖)分享简介:公共类上传{ProgressDialog对话框= NULL;INT serverResponse code = 0;字符串uploadFilePath = NULL;字符串uploadFileName = NULL;弦乐味精= NULL;字符串upLoadServerUri =htt​​p://192.168.1.1...

 公共类上传{ProgressDialog对话框= NULL;INT serverResponse code = 0;字符串uploadFilePath = NULL;字符串uploadFileName = NULL;弦乐味精= NULL;字符串upLoadServerUri =htt​​p://192.168.1.179/index.php;保护MainActivity语境;公共上传(MainActivity上下文){    this.context =背景;}公众诠释uploadFile(字符串sourceFileUri){    字符串文件名= sourceFileUri;    HttpURLConnection的康恩= NULL;    DataOutputStream类DOS = NULL;    字符串lineEnd = r  n;    串twoHyphens = - ;    字符串边界=*****;    INT读取动作,方bytesAvailable,缓冲区大小;    字节[]缓冲区;    INT MAXBUFFERSIZE = 1 * 1024 * 1024;    文件的资源文件=新的文件(sourceFileUri);    如果(!sourceFile.isFile()){        context.dialog.dismiss();        返回0;    }其他{        尝试{            //打开一个URL连接到这个Servlet            的FileInputStream的FileInputStream =新的FileInputStream(的资源文件);            网址URL =新的URL(upLoadServerUri);            //打开HTTP连接的URL            康恩=(HttpURLConnection类)url.openConnection();            conn.setDoInput(真); //允许输入            conn.setDoOutput(真); //允许输出            conn.setUseCaches(假); //不要使用缓存副本            conn.setRequestMethod(POST);            conn.setRequestProperty(连接,保持活动);            conn.setRequestProperty(ENCTYPE,多部分/表单数据);            conn.setRequestProperty(内容类型,的multipart / form-data的;边界=+边界);            conn.setRequestProperty(uploaded_file,文件名);            DOS =新的DataOutputStream类(conn.getOutputStream());            dos.writeBytes(twoHyphens +边界+ lineEnd);            dos.writeBytes(内容处置:表格数据;名称= uploaded_file ;文件名=                     +文件名++ lineEnd);            dos.writeBytes(lineEnd);            //创建最大大小的缓冲区            参考bytesAvailable = fileInputStream.available();            BUFFERSIZE = Math.min(方bytesAvailable,MAXBUFFERSIZE);            缓冲区=新的字节[缓冲区大小]            //读取文件,并将其写入形式...            读取动作= fileInputStream.read(缓冲液,0,缓冲区大小);            而(读取动作大于0){                dos.write(缓冲液,0,缓冲区大小);                参考bytesAvailable = fileInputStream.available();                BUFFERSIZE = Math.min(方bytesAvailable,MAXBUFFERSIZE);                读取动作= fileInputStream.read(缓冲液,0,缓冲区大小);            }            //发送文件数据后necesssary多部分的表单数据...            dos.writeBytes(lineEnd);            dos.writeBytes(twoHyphens +边界+ twoHyphens + lineEnd);            //服务器的响应(code和消息)            serverResponse code = conn.getResponse code();            串serverResponseMessage = conn.getResponseMessage();            Log.i(一个UploadFile,HTTP响应是:                    + serverResponseMessage +:+ serverResponse code);            如果(serverResponse code == 200){                InputStream为= conn.getInputStream();                RD的BufferedReader =新的BufferedReader(新的InputStreamReader(是));                串线;                StringBuffer的响应=新的StringBuffer();                而((行= rd.readLine())!= NULL){                    response.append(线);                    response.append(' r');                }                rd.close();                context.q_no.setText(响应);                fileInputStream.close();                dos.flush();                dos.close();                context.runOnUiThread(新的Runnable(){                    公共无效的run(){                        弦乐味精=是;                        //context.messageText.setText(msg);                        Toast.makeText(背景下,文件上传完成。                                Toast.LENGTH_SHORT).show();                    }                });            }     }赶上(MalformedURLException的前){     Log.e(上传文件到服务器,错误:+ ex.getMessage(),除息);        }赶上(例外五){            context.dialog.dismiss();            e.printStackTrace();            Log.e(上传文件到服务器异常,异常                    + e.getMessage(),E);        }        context.dialog.dismiss();        返回serverResponse code;     }  }} 

我想上面code捕捉到的图像,并上传到PHP server.it工作fine.when我上传图片服务器返回一个value.but当我尝试这个codeI得到下面的图像后,异常被上载到服务器和服务器响应。

  10月7日至27日:50:55.303:W / System.err的(4649):android.view.ViewRootImpl $ CalledFromWrongThreadException:只有创建视图层次原来的线程可以触摸它意见。 

解决方案 怎么将图片上传到服务器

您正在运行正常,上传上一个单独的线程(AsyncTask的?) - 不错。但是,任何时候你的UI(互动 .dialog.dismiss() .setText(...),等等),你需要在UI线程上运行此。

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 = "rn";
    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;

     }
  }
}

i tried above code to capture image and upload onto php server.it works fine.when i upload image server return a value.but when i try this code i get following exception after image is uploaded onto the server and the server response.

  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.

解决方案

You're correctly running upload on a separate thread (AsyncTask?) -- good. However, anytime you interact with the UI (.dialog.dismiss(), .setText(...), etc), you will need to run this on the UI thread.

阅读全文

相关推荐

最新文章