【问题标题】:Trying to use Async with image upload to webserver android?尝试使用异步将图像上传到网络服务器 android?
【发布时间】:2014-02-07 04:32:56
【问题描述】:

我正在尝试使用 Async 来提高效率并允许将图像上传到我的网络服务器我尝试了各种方法,但总是有一些不起作用...

这是我的最新代码,但如果我更改了 Int,则返回有问题
AsyncTask Int 然后它会出错,因为传递给它的 imagePath 是一个字符串...

这是错误

Type mismatch: cannot convert from int to String 

对于返回0并返回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);
    }

这是我正在努力解决的部分:

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

    }

【问题讨论】:

  • doInBackground() 接受String 有什么问题?另外,请尝试将您的代码最小化为最相关的代码。
  • 但请保留导入以供参考
  • @SherifelKhatib 真的吗?我会说干掉他们。它们占用了大量空间,通常很容易看出这是否是问题所在。
  • 第二个代码实际上是为了尝试使用有人在他们的 cmets 中回复我的不同方法来提出一个新问题,但我想同时展示这两个...导入...另外,如果我将其更改为字符串,那么我会收到 2 个返回的错误,指出它们不是字符串...因为它们是整数...负数是什么?
  • 您还有其他代码,不需要像其他方法一样最初使用(例如onActivityResult())。您应该按照您认为应该的方式进行说明,然后告诉我们您遇到的错误,以便我们帮助解决这些问题。例如,我不知道您将什么更改为 String 以及“2 返回”...我没有投反对票,但我猜是因为所有代码都没有解释清楚

标签: java android image


【解决方案1】:

我在这里看到了许多问题。首先,您几乎从不(如果有的话)想从AsyncTask 调用runOnUiThread()AsyncTask 的每个方法都在 UI 上运行,doInBackground() 除外,因此这通常不需要并且经常导致问题。根据您的操作,使用正确的方法更新 UI

其次,我认为您误解了 doInBackground() 正在返回的内容。它的结果返回到onPostExecute(),这是你的类声明中的第三个param

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

所以这意味着onPostExecute()(我没有看到你覆盖)应该期待String,这就是doInBackground()应该return。因此,如果您想将String 传递给onPostExecute(),则应将return 变量转换为String

AsyncTask Docs

通常

progressDialog.dismiss();

onPostExecute()

中被调用
progressDialog.show();

在使用AsyncTask 时将在onPreExecute() 中调用。那么您不必在您的onClick() 中创建新的Thread

【讨论】:

  • 你认为我是否需要 AsyncTask,因为我可以拿走 AsyncTask 并保持一切不变,现在它似乎工作正常,除了图像路径显示为 null 的事实?因为新线程和 runOnUiThread 基本上是在做 AsyncTask 已经做的事情吗?
  • 是的,只要你在后台运行网络代码Thread。但是AsyncTask 可以非常方便。我建议你看看我的建议,多读几遍文档(在你习惯之前它们很棘手),并学习如何正确使用它。
  • 好的,我在没有异步的情况下更新了代码,但是感谢这绝对有助于清除异步任务...顺便说一句,您知道为什么当我选择要上传的图像时为什么路径显示为空?它与这里的代码有关,我相信 public void onActivityResult(int requestCode, int resultCode, Intent data) {
  • 我没有多看它。设置一些断点,看看会是什么null
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-12-07
  • 2014-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-28
相关资源
最近更新 更多