java - 尝试使用异步将图像上传到 Android 网络服务器?

标签 java android image

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

这是我的最新代码,但返回 Int 时遇到问题,如果我更改
AsyncTask Int 然后它会出错,因为传递给它的 imagePath 是一个 String...

这是错误

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

    }

最佳答案

我在这里看到了很多问题。首先,你几乎从来不想(如果有的话)调用 runOnUiThread()来自AsyncTaskAsyncTask的每一个方法运行于 UI除了 doInBackground()所以这通常是不需要的,并且经常会导致问题。更新UI根据您正在做的事情使用正确的方法。

第二,我认为你误解了什么doInBackground()正在返回。其结果返回为onPostExecute()这是第三个param在你的类声明中

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

所以这意味着 onPostExecute() (我没有看到你压倒一切)应该期待 String这就是 doInBackground()应该return 。所以你应该转换你的 return变量为String如果你想通过 StringonPostExecute()

AsyncTask Docs

通常

progressDialog.dismiss();

onPostExecute() 中调用和

progressDialog.show();

将在 onPreExecute() 中调用当使用AsyncTask时。那么你就不必创建一个新的 Thread在你的onClick() .

关于java - 尝试使用异步将图像上传到 Android 网络服务器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21192778/

相关文章:

java - 尝试在我的 Spring 项目中获取 InputStream 时出现 Http 502 错误

android - 无法获取提供程序 android.arch.lifecycle.LifecycleRuntimeTrojanProvider : java. lang.ClassNotFoundException

Android:如何使用 Canvas /绘制位图缩放位图以适合屏幕大小?

Python PIL ImageTk.PhotoImage() 给我一个总线错误?

java - 应用程序无法在 Activity 之间传递值

java - 在 Java 中获取给定周数、星期几和年份的日期

android - 如何删除traces.txt

java - 计算图像位移 - Java

javascript - 如何使用一个 png 图像创建多个网站按钮(及其悬停)

java - 为什么堆栈使用数组为什么不使用链表