发送图像OutputStream

时间:2017-08-08 20:41:24

标签: android httprequest

我正在尝试在Android中制作图片上传应用程序。我要求用户选择图像,然后将图像转换为输出流。然后我在名为UploadImage的类中使用AsyncTask。我收到了我无法发送图片的错误,因为它不是Stringenter image description here

我正在使用Http-Request类将数据从Android发送到PHP。

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            Uri selectedImageUri = data.getData();
            try {
                InputStream in = getContentResolver().openInputStream(selectedImageUri);
                OutputStream out = new FileOutputStream(new File("your_file_here"));

                byte[] buf = new byte[1024];
                int len;
                while ((len = in.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }

                TextView textViewDynamicText = (TextView) findViewById(R.id.textViewDynamicText); // Dynamic text
                String apiURL = "https://website.com/image_upload/image_upload.php";
                UploadImage task = new UploadImage(this, apiURL, out,
                        textViewDynamicText, new UploadImage.TaskListener() {
                    @Override
                    public void onFinished(String result) {
                        // Do Something after the task has finished
                        imageUploadResult();
                    }
                });
                task.execute();


                out.close();
                in.close();
            }
            catch (java.io.FileNotFoundException e) {
                Toast.makeText(this, "java.io.FileNotFoundException: " + e.toString(), Toast.LENGTH_LONG).show();
            }
            catch (java.io.IOException e) {
                Toast.makeText(this, "java.io.IOException: " + e.toString(), Toast.LENGTH_LONG).show();
            }

        } // RESULT_OK
    } // onActivityResult

UploadImage类:

import android.content.Context;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Environment;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;

/**
 * Created by bruker on 08.08.2017.
 */

public class UploadImage extends AsyncTask<String, Void, String> {

    /* Class variables */
    private Context context; // Holder (this)
    private String  apiUrl; // URL for image upload form, example http://website.com/image_upload.php
    private TextView dynamicText;
    private OutputStream out;

    private final UploadImage.TaskListener taskListener; // This is the reference to the associated listener


    public interface TaskListener {
        public void onFinished(String result);
    }

    /*- Constructor GET, SEND --------------------------------------------------------------- */
    public UploadImage(Context ctx, String applicationPIUrl, OutputStream output, TextView textViewDynamicText, UploadImage.TaskListener listener) {
        context             = ctx;
        apiUrl              = applicationPIUrl;
        out                 = output;
        dynamicText         = textViewDynamicText;
        this.taskListener   = listener; // The listener reference is passed in through the constructor
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        dynamicText.setText("Loading...");
    }


    @Override
    protected String doInBackground(String... params) {
        // Run methods
        String stringResponse ="";
        try {
            try{
                // Send image
                HttpRequest request = HttpRequest.post(apiUrl); // Post form
                request.part("inp_image", out); // send form image
                stringResponse = request.body();
            }
            catch (Exception e){
                return e.toString();
            }
        }
        catch(Exception e){
            return e.toString();
        }
        return stringResponse;
    }

    @Override
    protected void onPostExecute(String result) {
        // Set text view with result string
        if(dynamicText == null){
            Toast.makeText(context, "NULL", Toast.LENGTH_SHORT).show();
        }
        else {
            dynamicText.setText(result);
        }
        // In onPostExecute we check if the listener is valid
        if(this.taskListener != null) {
            // And if it is we call the callback function on it.
            this.taskListener.onFinished(result);
        }
    }

    @Override
    protected void onProgressUpdate(Void... values) {}

}

1 个答案:

答案 0 :(得分:1)

可能有些令人困惑,HttpRequest.part() takes an InputStream, not an OutputStream。它实际上使您的代码更简单,因为您不必执行那么奇怪的事情,您将所有内容从InputStream复制到OutputStream。这应该有效:

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            Uri selectedImageUri = data.getData();
            try {
                InputStream in = getContentResolver().openInputStream(selectedImageUri);

                TextView textViewDynamicText = (TextView) findViewById(R.id.textViewDynamicText); // Dynamic text
                String apiURL = "https://website.com/image_upload/image_upload.php";
                UploadImage task = new UploadImage(this, apiURL, in,
                        textViewDynamicText, new UploadImage.TaskListener() {
                    @Override
                    public void onFinished(String result) {
                        // Do Something after the task has finished
                        imageUploadResult();
                    }
                });
                task.execute();

                in.close();
            }
            catch (java.io.FileNotFoundException e) {
                Toast.makeText(this, "java.io.FileNotFoundException: " + e.toString(), Toast.LENGTH_LONG).show();
            }
            catch (java.io.IOException e) {
                Toast.makeText(this, "java.io.IOException: " + e.toString(), Toast.LENGTH_LONG).show();
            }

        } // RESULT_OK
    } // onActivityResult

在UploadImage中:

import android.content.Context;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Environment;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.InputStream;

/**
 * Created by bruker on 08.08.2017.
 */

public class UploadImage extends AsyncTask<String, Void, String> {

    /* Class variables */
    private Context context; // Holder (this)
    private String  apiUrl; // URL for image upload form, example http://website.com/image_upload.php
    private TextView dynamicText;
    private InputStream in;

    private final UploadImage.TaskListener taskListener; // This is the reference to the associated listener


    public interface TaskListener {
        public void onFinished(String result);
    }

    /*- Constructor GET, SEND --------------------------------------------------------------- */
    public UploadImage(Context ctx, String applicationPIUrl, InputStream input, TextView textViewDynamicText, UploadImage.TaskListener listener) {
        context             = ctx;
        apiUrl              = applicationPIUrl;
        in                  = input;
        dynamicText         = textViewDynamicText;
        this.taskListener   = listener; // The listener reference is passed in through the constructor
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        dynamicText.setText("Loading...");
    }


    @Override
    protected String doInBackground(String... params) {
        // Run methods
        String stringResponse ="";
        try {
            try{
                // Send image
                HttpRequest request = HttpRequest.post(apiUrl); // Post form
                request.part("inp_image", in); // send form image
                stringResponse = request.body();
            }
            catch (Exception e){
                return e.toString();
            }
        }
        catch(Exception e){
            return e.toString();
        }
        return stringResponse;
    }

    @Override
    protected void onPostExecute(String result) {
        // Set text view with result string
        if(dynamicText == null){
            Toast.makeText(context, "NULL", Toast.LENGTH_SHORT).show();
        }
        else {
            dynamicText.setText(result);
        }
        // In onPostExecute we check if the listener is valid
        if(this.taskListener != null) {
            // And if it is we call the callback function on it.
            this.taskListener.onFinished(result);
        }
    }

    @Override
    protected void onProgressUpdate(Void... values) {}

}