首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >发送图片OutputStream

发送图片OutputStream
EN

Stack Overflow用户
提问于 2017-08-09 04:41:24
回答 1查看 1.4K关注 0票数 0

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

我使用Http-Request类从安卓发送数据到PHP。

代码语言:javascript
复制
@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类:

代码语言:javascript
复制
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) {}

}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-08-09 04:55:36

也许有点令人困惑,HttpRequest.part() takes an InputStream, not an OutputStream。它实际上使您的代码变得更简单,因为您不必做那些从InputStream复制到OutputStream的奇怪事情。这应该是可行的:

代码语言:javascript
复制
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中:

代码语言:javascript
复制
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) {}

}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45577680

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档