尝试使用异步与图片上传到web服务器的Andr​​oid? [英] Trying to use Async with image upload to webserver android?

查看:158
本文介绍了尝试使用异步与图片上传到web服务器的Andr​​oid?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用异步更有效率并允许图像上传到我的web服务器我已经尝试了各种方法,但总有一些东西不工作...

下面是我最新的code,但具有回报作为一个诠释,如果我改变结果的问题
 AsyncTask的诠释则错误,因为被传递给它的ImagePath是一个String ...

这是错误

 类型不匹配:不能从int到String转换

有关返回0,并返回serverResponse code;

 公共类衣柜扩展活动实现OnClickListener {    //为字段设置变量
    私人的EditText名称字段,sizeField,colorField,quantityField;
    私人微调TYPEFIELD,seasonField;
    私人ImageView的ImageView的;
    私人进度progressBarField;
    私人TextView的imageTextSelect,resImage;
    私人ProgressDialog progressDialog = NULL;
    私人诠释serverResponse code = 0;
    私人按钮uploadImageButton,postWardrobe;
    私人字符串upLoadServerUri = NULL;
    私有String的ImagePath = NULL;    @覆盖
    保护无效的onCreate(捆绑savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.wardrobe);        //图片上传的东西
        ImageView的=(ImageView的)findViewById(R.id.user_photo);
        imageTextSelect =(的TextView)findViewById(R.id.imageTextSelect);        //按钮上传图片
        uploadImageButton =(按钮)findViewById(R.id.uploadImageButton);        //张贴详细信息按钮
        postWardrobe =(按钮)findViewById(R.id.postButton);        uploadImageButton.setOnClickListener(本);
        postWardrobe.setOnClickListener(本);
    @覆盖
    公共无效的onClick(视图v){
        如果(V == uploadImageButton){
            //下面可以打开手机图库
            意向意图=新的Intent();
            intent.setType(图像/ *);
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(
                    Intent.createChooser(原意,使用完整的行动),1);
        }
        如果(V == postWardrobe){
            //验证输入,并曾进入的东西
            如果(nameField.getText()的toString()长()< 1。
                    || 。colorField.getText()的toString()长()< 1
                    || 。sizeField.getText()的toString()长()< 1
                    || 。quantityField.getText()的toString()长()< 1){                //缺少必要的信息(空了这一点,但让我们看看)
                Toast.makeText(getApplicationContext(),
                        请填写所有栏目!,Toast.LENGTH_LONG)
                        。显示();
            }其他{
                JSONObject的dataWardrobe =新的JSONObject();                尝试{
                    dataWardrobe.put(类型,typeField.getSelectedItem()
                            的ToString());
                    dataWardrobe.put(色,colorField.getText()的toString());
                    dataWardrobe.put(旺季,seasonField.getSelectedItem()
                            的ToString());
                    dataWardrobe.put(大小,sizeField.getText()的toString());
                    dataWardrobe.put(量,quantityField.getText()
                            的ToString());                }赶上(JSONException E){
                    // TODO自动生成catch块
                    e.printStackTrace();
                }                //使进度条可见
                progressBarField.setVisibility(View.VISIBLE);                //执行POST请求
                新dataSend()执行(dataWardrobe);                //下面的图片
                progressDialog = ProgressDialog.show(wardrobe.this,,
                        上传文件...,真正的);
                imageTextSelect.setText(上传开始......);
                新主题(新的Runnable接口(){
                    公共无效的run(){                        doFileUpload(的ImagePath);                    }
                })。开始();
            }
        }    }    公共无效的onActivityResult(INT申请code,INT结果code,意图数据){
        如果(结果code == RESULT_OK&放大器;&安培;请求code == 1){
            //位图的照片=(位图)data.getData()的getPath()。            乌里selectedImageUri = data.getData();
            的ImagePath =的getPath(selectedImageUri);
            位图位图= BitmapFactory.de codeFILE(的ImagePath);
            imageview.setImageBitmap(位图);            //添加到文本视图中添加了什么
            imageTextSelect.setText(上传文件路径:+的ImagePath);
        }
    }    公共字符串的getPath(URI URI){
        的String [] =投影{MediaStore.Images.Media.DATA};
        光标光标= getContentResolver()查询(URI,投影,NULL,NULL,
                空值);
        INT与Column_Index =光标
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        返回cursor.getString(Column_Index中);
    }

这里是我挣扎的部分:

 公众诠释doFileUpload(字符串sourceFileUri){
        字符串upLoadServerUri =htt​​p://10.0.2.2/wardrobe;
        字符串文件名=的ImagePath;        HttpURLConnection的康恩= NULL;
        DataOutputStream类DOS = NULL;
        字符串lineEnd =\\ r \\ n;
        串twoHyphens = - ;
        字符串边界=*****;
        INT读取动作,方bytesAvailable,缓冲区大小;
        字节[]缓冲区;
        INT MAXBUFFERSIZE = 1 * 1024 * 1024;
        文件的资源文件=新的文件(的ImagePath);        如果(!sourceFile.isFile()){            progressDialog.dismiss();            Log.e(一个UploadFile,源文件不存在:+的ImagePath);            runOnUiThread(新的Runnable(){
                公共无效的run(){
                    imageTextSelect.setText(源文件不存在
                            +的ImagePath);
                }
            });            返回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){                    runOnUiThread(新的Runnable(){
                        公共无效的run(){
                            弦乐味精=文件上传完成\\ n \\ n看到这里上传的文件:\\ n \\ n
                                    +F:/ WAMP / WAMP / WWW /上传
                            imageTextSelect.setText(MSG);
                            Toast.makeText(wardrobe.this,
                                    文件上传完成。Toast.LENGTH_SHORT)
                                    。显示();
                        }
                    });
                }                //关闭流//
                fileInputStream.close();
                dos.flush();
                dos.close();            }赶上(MalformedURLException的前){                progressDialog.dismiss();
                ex.printStackTrace();                runOnUiThread(新的Runnable(){
                    公共无效的run(){
                        imageTextSelect
                                .setText(MalformedURLException的例外情况:检查脚本网址。);
                        Toast.makeText(wardrobe.this,MalformedURLException的
                                Toast.LENGTH_SHORT).show();
                    }
                });                Log.e(上传文件到服务器,错误:+ ex.getMessage(),除息);
            }赶上(例外五){                progressDialog.dismiss();
                e.printStackTrace();                runOnUiThread(新的Runnable(){
                    公共无效的run(){
                        imageTextSelect.setText(得到例外:看到logcat的);
                        Toast.makeText(wardrobe.this,
                                得到例外:看到logcat的
                                Toast.LENGTH_SHORT).show();
                    }
                });
                Log.e(上传文件到服务器异常
                        例外:+ e.getMessage(),E);
            }
            progressDialog.dismiss();
            返回serverResponse code;        } //结束else块    }


解决方案

我在这里看到很多的几个问题。首先,你几乎从来没有(如果有的话),要调用 runOnUiThread()的AsyncTask 的AsyncTask 的每一个方法上的 UI 除了 doInBackground()所以这通常是不需要的,往往会产生问题。更新 UI 与这取决于你在做什么正确的方法。

第二,我想你误会什么 doInBackground()正在恢复。其结果返回给 onPostExecute()这是第三参数在你的类声明

 私有类doFileUpload扩展的AsyncTask<弦乐,太虚,字符串> {

因此​​,这意味着 onPostExecute()(我不知道你重写)应该期待一个字符串而这正是 doInBackground()收益。所以,你应该转换收益变量字符串如果你想传递一个字符串 onPostExecute()

AsyncTask的文档

通常

  progressDialog.dismiss();

被称为 onPostExecute()

  progressDialog.show();

将于算得上preExecute()使用的AsyncTask 。然后,你不必在创建一个新的你的的onClick()

I am trying to use Async to be more efficient and to allow for image uploads to my webserver I have tried various methods but there is always something not working...

Here is my latest code but having problems with the return being an Int and if I change the
AsyncTask Int then it errors because the imagePath being passed to it is a String...

This is the error

Type mismatch: cannot convert from int to String 

For return 0 and return serverResponseCode;

public class wardrobe extends Activity implements OnClickListener {

    // set variable for the fields
    private EditText nameField, sizeField, colorField, quantityField;
    private Spinner typeField, seasonField;
    private ImageView imageview;
    private ProgressBar progressBarField;
    private TextView imageTextSelect, resImage;
    private ProgressDialog progressDialog = null;
    private int serverResponseCode = 0;
    private Button uploadImageButton, postWardrobe;
    private String upLoadServerUri = null;
    private String imagepath = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.wardrobe);

        // image upload stuff
        imageview = (ImageView) findViewById(R.id.user_photo);
        imageTextSelect = (TextView) findViewById(R.id.imageTextSelect);

        // button for upload image
        uploadImageButton = (Button) findViewById(R.id.uploadImageButton);

        // button for posting details
        postWardrobe = (Button) findViewById(R.id.postButton);

        uploadImageButton.setOnClickListener(this);
        postWardrobe.setOnClickListener(this);


    @Override
    public void onClick(View v) {
        if (v == uploadImageButton) {
            // below allows you to open the phones gallery
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(
                    Intent.createChooser(intent, "Complete action using"), 1);
        }
        if (v == postWardrobe) {
            // validate input and that something was entered
            if (nameField.getText().toString().length() < 1
                    || colorField.getText().toString().length() < 1
                    || sizeField.getText().toString().length() < 1
                    || quantityField.getText().toString().length() < 1) {

                // missing required info (null was this but lets see)
                Toast.makeText(getApplicationContext(),
                        "Please complete all sections!", Toast.LENGTH_LONG)
                        .show();
            } else {
                JSONObject dataWardrobe = new JSONObject();

                try {
                    dataWardrobe.put("type", typeField.getSelectedItem()
                            .toString());
                    dataWardrobe.put("color", colorField.getText().toString());
                    dataWardrobe.put("season", seasonField.getSelectedItem()
                            .toString());
                    dataWardrobe.put("size", sizeField.getText().toString());
                    dataWardrobe.put("quantity", quantityField.getText()
                            .toString());

                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                // make progress bar visible
                progressBarField.setVisibility(View.VISIBLE);

                // execute the post request
                new dataSend().execute(dataWardrobe);

                // image below
                progressDialog = ProgressDialog.show(wardrobe.this, "",
                        "Uploading file...", true);
                imageTextSelect.setText("uploading started.....");
                new Thread(new Runnable() {
                    public void run() {

                        doFileUpload(imagepath);

                    }
                }).start();
            }
        }

    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK && requestCode == 1) {
            // Bitmap photo = (Bitmap) data.getData().getPath();

            Uri selectedImageUri = data.getData();
            imagepath = getPath(selectedImageUri);
            Bitmap bitmap = BitmapFactory.decodeFile(imagepath);
            imageview.setImageBitmap(bitmap);

            // add to text view what was added
            imageTextSelect.setText("Uploading file path: " + imagepath);
        }
    }

    public String getPath(Uri uri) {
        String[] projection = { MediaStore.Images.Media.DATA };
        Cursor cursor = getContentResolver().query(uri, projection, null, null,
                null);
        int column_index = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }

Here is the part I am struggling with:

public int doFileUpload(String sourceFileUri) {
        String upLoadServerUri = "http://10.0.2.2/wardrobe";
        String fileName = imagepath;

        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(imagepath);

        if (!sourceFile.isFile()) {

            progressDialog.dismiss();

            Log.e("uploadFile", "Source File not exist :" + imagepath);

            runOnUiThread(new Runnable() {
                public void run() {
                    imageTextSelect.setText("Source File not exist :"
                            + imagepath);
                }
            });

            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) {

                    runOnUiThread(new Runnable() {
                        public void run() {
                            String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
                                    + " F:/wamp/wamp/www/uploads";
                            imageTextSelect.setText(msg);
                            Toast.makeText(wardrobe.this,
                                    "File Upload Complete.", Toast.LENGTH_SHORT)
                                    .show();
                        }
                    });
                }

                // close the streams //
                fileInputStream.close();
                dos.flush();
                dos.close();

            } catch (MalformedURLException ex) {

                progressDialog.dismiss();
                ex.printStackTrace();

                runOnUiThread(new Runnable() {
                    public void run() {
                        imageTextSelect
                                .setText("MalformedURLException Exception : check script url.");
                        Toast.makeText(wardrobe.this, "MalformedURLException",
                                Toast.LENGTH_SHORT).show();
                    }
                });

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

                progressDialog.dismiss();
                e.printStackTrace();

                runOnUiThread(new Runnable() {
                    public void run() {
                        imageTextSelect.setText("Got Exception : see logcat ");
                        Toast.makeText(wardrobe.this,
                                "Got Exception : see logcat ",
                                Toast.LENGTH_SHORT).show();
                    }
                });
                Log.e("Upload file to server Exception",
                        "Exception : " + e.getMessage(), e);
            }
            progressDialog.dismiss();
            return serverResponseCode;

        } // End else block

    }

解决方案

I see many several problems here. First, you almost never (if ever) want to call runOnUiThread() from AsyncTask. Every method of AsyncTask runs on the UI except for doInBackground() so this usually isn't needed and often causes problems. Update the UI with the correct methods depending on what you are doing.

Second, I think you misunderstand what doInBackground() is returning. Its result is returned to onPostExecute() which is the 3rd param in your class declaration

private class doFileUpload extends AsyncTask <String, Void, String> {

So this means that onPostExecute() (which I don't see you overriding) should expect a String and that is what doInBackground() should return. So you should convert your return variables to String if you want to pass a String to onPostExecute()

AsyncTask Docs

Typically

progressDialog.dismiss();

is called in onPostExecute() and

progressDialog.show();

would be called in onPreExecute() when using an AsyncTask. Then you don't have to create a new Thread in your onClick().

这篇关于尝试使用异步与图片上传到web服务器的Andr​​oid?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆