【问题标题】:android unable to upload image to serverandroid无法上传图片到服务器
【发布时间】:2017-05-04 11:00:34
【问题描述】:

我是 android 的新手。因为最近几天我在将图像发送到服务器时遇到了一些问题。我只是有一个表单,其中包含一些要从库中获取的文本字段和图像。除了图像上传之外,一切都运行良好。我在谷歌上尝试了大多数教程。主要问题是 logcat 没有显示任何错误。我无法跟踪什么实际上出错了。 这就是我所做的

我使用此代码从 galary 获取图像

 private void showFileChooser() {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
    }

 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
            filePath = data.getData();
            try {
                bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
                schoolLogoUpload.setImageBitmap(bitmap);

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

我写了这个函数来发送选择的图像到服务器

public String getPath(Uri uri) {
        Cursor cursor = getContentResolver().query(uri, null, null, null, null);
        cursor.moveToFirst();
        String document_id = cursor.getString(0);
        document_id = document_id.substring(document_id.lastIndexOf(":") + 1);
        cursor.close();

        cursor = getContentResolver().query(
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                null, MediaStore.Images.Media._ID + " = ? ", new String[]{document_id}, null);
        cursor.moveToFirst();
        String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
        cursor.close();

        return path;
    }


public void uploadMultipart() {
        //getting the actual path of the image
        String path = getPath(filePath);

        //Uploading code
        try {
            String uploadId = UUID.randomUUID().toString();

            //Creating a multi part request
            new MultipartUploadRequest(this, uploadId, UPLOAD_URL)
                    .addFileToUpload(path, "image") //Adding file
                    .setNotificationConfig(new UploadNotificationConfig())
                    .setMaxRetries(2)
                    .startUpload(); //Starting the upload

        } catch (Exception exc) {
            Toast.makeText(this, exc.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

这是我在服务器端接收图像数据的代码

if(Input::hasFile('image')) {
            $file = Input::file('image');
            $destination_path = "uploads";
            $extension = Input::file('image')->getClientOriginalExtension();
            $file_name = str_random(20). "." . $extension;
            Input::file('image')->move($destination_path, $file_name);
        }else{
            return \Response::json([
                "error"=>["message"=>"Please select the college logo"]
            ], 404);

【问题讨论】:

  • 你在哪里打电话uploadMultipart()
  • 您还想将exc.printStackTrace() 添加到您的方法中。
  • @mad_manny 我在按钮内调用该函数,将数据发送到服务器。你能帮帮我吗?

标签: android image server


【解决方案1】:

我假设您已将图像转换为Base64 格式。基本上Base64 格式将图像(或编码图像)转换为String 格式。

* 写一个Asynctask 会为你上传一张图片到服务器*

下面是Asynctask :-

private class AsyncUploadToServer extends AsyncTask<String, Void, String>
{
    ProgressDialog pdUpload;

    String imageData = "";

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pdUpload = new ProgressDialog(MainActivity.this);
        pdUpload.setMessage("Uploading...");
        pdUpload.show();
    }

    @Override
    protected String doInBackground(String... params)
    {
        imageData = params[0];
        HttpClient httpclient = new DefaultHttpClient();

        // URL where data to be uploaded
        HttpPost httppost = new HttpPost(YOUR_URL_HERE);

        try
        {
            // adding data
            List<NameValuePair> dataToBeAdd = new ArrayList<>();
            dataToBeAdd.add(new BasicNameValuePair("uploadedImage", imageData));
            httppost.setEntity(new UrlEncodedFormEntity(dataToBeAdd));

            // execute http post request
            HttpResponse response = httpclient.execute(httppost);
            Log.i("MainActivity", "Response: " + response);
        }
        catch (ClientProtocolException ex)
        {
            ex.printStackTrace();
        }
        catch (IOException ioe)
        {
            ioe.printStackTrace();
        }
        return "";
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        pdUpload.dismiss();
        Toast.makeText(getApplicationContext(), "Image Uploaded Successfully..!!", Toast.LENGTH_SHORT).show();
    }
}

希望这会对您有所帮助。 :-)

P.S.:- 如果你对 asynctask 不太了解,这里是链接https://developer.android.com/reference/android/os/AsyncTask.html

【讨论】:

  • 先生,我应该在哪里添加此代码。我必须用这个替换我上面的代码还是这是一个完整的代码,允许我将图像上传到服务器。请帮助
  • 是的,你可以用这个替换你的代码。你只需要在按钮点击事件上调用这个异步任务。
  • 我想知道如何在按钮内调用一个类。接下来是我选择的图像如何连接到您上面建议的类。
  • 基本上,您必须在按钮单击事件上执行该异步任务,并将图像作为参数。使用 Base64 格式编码后,您的图像将采用字符串格式。只需阅读有关 Asynctask 以及如何将值传递给它的信息。还有如何在点击按钮时执行异步任务。
  • 但我并不是要使用 base64 发送图像。我希望在不使用 base64 编码器的情况下发送图像
猜你喜欢
  • 1970-01-01
  • 2018-05-08
  • 1970-01-01
  • 1970-01-01
  • 2014-06-05
  • 2014-07-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多