如何将图像文件上传到heroku

How to upload image file to heroku

我目前正在使用部署在 Heroku 中的机器学习模型开发 android 植物识别应用。我使用在我的应用程序中实现的相机捕获图像,我想将该图像发送到部署在 heroku 中的 api,然后它将预测图像并以字符串格式向我发送响应,告诉我们它是哪个物种属于.

public class MainActivity extends AppCompatActivity {
private final int CAMERA_REQ_CODE=100;
private final int GALLERY_REQ_CODE=1000;
ImageView imgCam;

Bitmap img;
String url = "https://medkit.herokuapp.com/predict";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    imgCam=findViewById(R.id.imgCamera);
    Button btnCamera=findViewById(R.id.btnCamera);
    Button btnGallery=findViewById(R.id.btnGallery);
    Button btnPredict=findViewById(R.id.btnPredict);
    TextView result=findViewById(R.id.resultText);


    btnCamera.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent iCamera=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(iCamera,CAMERA_REQ_CODE);
        }
    });
    btnGallery.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent iGallery=new Intent(Intent.ACTION_PICK);
            iGallery.setData(MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(iGallery,GALLERY_REQ_CODE);

        }
    });
    btnPredict.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        String data = jsonObject.getString("y_pred_mobile");
                        if (data.equals("1")) {
                            result.setText("Hibiscus");
                        } else if (data.equals("2")) {
                            result.setText("Aloevera");
                        } else if (data.equals("3")) {
                            result.setText("Brahmi");
                        } else if (data.equals("4")) {
                            result.setText("Neem");
                        } else {
                            result.setText("not in the selected species");
                        }


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


                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(MainActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();

                }
            }) {@override
                 protected Map<String,String> getParams(){
                    Map<String,String> params = new HashMap<String,String>();
                    params.put("cgpa",cgpa.getText().toString());
                    params.put("iq",iq.getText().toString());
                    params.put("profile_score",profile_score.getText().toString());

                    return params;

                }

            };
            RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
            queue.add(stringRequest);




        }
    });
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if(resultCode==RESULT_OK)
    {
        if(requestCode==CAMERA_REQ_CODE)
        {
            //for camera
            Bitmap img=(Bitmap)(data.getExtras().get("data"));
            imgCam.setImageBitmap(img);

        }
        if(requestCode==GALLERY_REQ_CODE)
        {
            //for Gallery
            imgCam.setImageURI(data.getData());
        }
    }
}

} ` 以上是我的应用程序代码。休息一切正常,但我需要一个代码来放置图像而不是字符串,例如

@Override
                protected Map<String,String> getParams(){
                    Map<String,String> params = new HashMap<String,String>();
                    params.put("cgpa",cgpa.getText().toString());
                    params.put("iq",iq.getText().toString());
                    params.put("profile_score",profile_score.getText().toString());

                    return params;

这段代码是将字符串作为数据发送,我需要一个可以将图像作为数据发送到 api 的代码,而不是上面代码中的字符串

谁能帮我解决这个问题?

我假设您正在尝试将位图图像上传到您的 Heroku 服务器。那么下面的代码示例可以帮助你。

创建一个 class VolleyMultipartRequest 如下所示。 class 允许 MultiPart 个文件被发送到服务器。

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Map;

public class VolleyMultipartRequest extends Request<NetworkResponse> {

    private final String twoHyphens = "--";
    private final String lineEnd = "\r\n";
    private final String boundary = "APIClient-" + System.currentTimeMillis ();
    private final Response.Listener<NetworkResponse> mListener;
    private final Response.ErrorListener mErrorListener;

    public VolleyMultipartRequest ( int method, String url, Response.Listener<NetworkResponse> listener, Response.ErrorListener errorListener ) {
        super ( method, url, errorListener );
        this.mListener = listener;
        this.mErrorListener = errorListener;
    }

    @Override
    public Map<String, String> getHeaders () throws AuthFailureError {
        return super.getHeaders ();
    }

    @Override
    public String getBodyContentType () {
        return "multipart/form-data;boundary=" + boundary;
    }

    @Override
    public byte[] getBody () throws AuthFailureError {
        ByteArrayOutputStream bos = new ByteArrayOutputStream ();
        DataOutputStream dos = new DataOutputStream ( bos );
        try {
            // populate text payload
            Map<String, String> params = getParams ();
            if (params != null && params.size () > 0) {
                textParse ( dos, params, getParamsEncoding () );
            }
            // populate data byte payload
            Map<String, DataPart> data = getByteData ();
            if (data != null && data.size () > 0) {
                dataParse ( dos, data );
            }
            // close multipart form data after text and file data
            dos.writeBytes ( twoHyphens + boundary + twoHyphens + lineEnd );
            return bos.toByteArray ();
        } catch (IOException e) {
            e.printStackTrace ();
        }
        return null;
    }

    /**
     * Custom method handle data payload.
     *
     * @return Map data part label with data byte
     */
    protected Map<String, DataPart> getByteData () {
        return null;
    }

    @Override
    protected Response<NetworkResponse> parseNetworkResponse ( NetworkResponse response ) {
        try {
            return Response.success ( response, HttpHeaderParser.parseCacheHeaders ( response ) );
        } catch (Exception e) {
            return Response.error ( new ParseError ( e ) );
        }
    }

    @Override
    protected void deliverResponse ( NetworkResponse response ) {
        mListener.onResponse ( response );
    }

    @Override
    public void deliverError ( VolleyError error ) {
        mErrorListener.onErrorResponse ( error );
    }

    /**
     * Parse string map into data output stream by key and value.
     *
     * @param dataOutputStream data output stream handle string parsing
     * @param params           string inputs collection
     * @param encoding         encode the inputs, default UTF-8
     * @throws IOException IOException
     */
    private void textParse ( DataOutputStream dataOutputStream, Map<String, String> params, String encoding ) throws IOException {
        try {
            for (Map.Entry<String, String> entry : params.entrySet ()) {
                buildTextPart ( dataOutputStream, entry.getKey (), entry.getValue () );
            }
        } catch (UnsupportedEncodingException uee) {
            throw new RuntimeException ( "Encoding not supported: " + encoding, uee );
        }
    }

    /**
     * Parse data into data output stream.
     *
     * @param dataOutputStream data output stream handle file attachment
     * @param data             loop through data
     * @throws IOException IOException
     */
    private void dataParse ( DataOutputStream dataOutputStream, Map<String, DataPart> data ) throws IOException {
        for (Map.Entry<String, DataPart> entry : data.entrySet ()) {
            buildDataPart ( dataOutputStream, entry.getValue (), entry.getKey () );
        }
    }

    /**
     * Write string data into header and data output stream.
     *
     * @param dataOutputStream data output stream handle string parsing
     * @param parameterName    name of input
     * @param parameterValue   value of input
     * @throws IOException IOException
     */
    private void buildTextPart ( DataOutputStream dataOutputStream, String parameterName, String parameterValue ) throws IOException {
        dataOutputStream.writeBytes ( twoHyphens + boundary + lineEnd );
        dataOutputStream.writeBytes ( "Content-Disposition: form-data; name=\"" + parameterName + "\"" + lineEnd );
        dataOutputStream.writeBytes ( lineEnd );
        dataOutputStream.writeBytes ( parameterValue + lineEnd );
    }

    /**
     * Write data file into header and data output stream.
     *
     * @param dataOutputStream data output stream handle data parsing
     * @param dataFile         data byte as DataPart from collection
     * @param inputName        name of data input
     * @throws IOException IOException
     */
    private void buildDataPart ( DataOutputStream dataOutputStream, DataPart dataFile, String inputName ) throws IOException {
        dataOutputStream.writeBytes ( twoHyphens + boundary + lineEnd );
        dataOutputStream.writeBytes ( "Content-Disposition: form-data; name=\"" +
                inputName + "\"; filename=\"" + dataFile.getFileName () + "\"" + lineEnd );
        dataOutputStream.writeBytes ( lineEnd );
        ByteArrayInputStream fileInputStream = new ByteArrayInputStream ( dataFile.getContent () );
        int bytesAvailable = fileInputStream.available ();
        int maxBufferSize = 1024 * 1024;
        int bufferSize = Math.min ( bytesAvailable, maxBufferSize );
        byte[] buffer = new byte[bufferSize];
        int bytesRead = fileInputStream.read ( buffer, 0, bufferSize );
        while (bytesRead > 0) {
            dataOutputStream.write ( buffer, 0, bufferSize );
            bytesAvailable = fileInputStream.available ();
            bufferSize = Math.min ( bytesAvailable, maxBufferSize );
            bytesRead = fileInputStream.read ( buffer, 0, bufferSize );
        }
        dataOutputStream.writeBytes ( lineEnd );
    }

    public static class DataPart {
        private final String fileName;
        private final byte[] content;

        DataPart ( String name, byte[] data ) {
            fileName = name;
            content = data;
        }

        String getFileName () {
            return fileName;
        }

        byte[] getContent () {
            return content;
        }
    }
}

添加上面的class后,调用下面的uploadImage方法。将您从相机或画廊收到的 bitmap 传递给此方法

/**
 * This method sends bitmap image to backend server
 * 
 * @param bitmap
 */
public void uploadImage ( final Bitmap bitmap ) {
    VolleyMultipartRequest volleyMultipartRequest = new VolleyMultipartRequest ( Request.Method.POST,
            "YOUR_IMAGE_UPLOAD_URL",
            this::showSuccessMessage,
            this::showErrorMessage
    ) {
        @Override
        protected Map<String, DataPart> getByteData () {
            Map<String, DataPart> params = new HashMap<> ();
            long imageName = System.currentTimeMillis ();
            params.put ( "image", new DataPart ( imageName + ".jpg", getFileDataFromDrawable ( bitmap ) ) );
            return params;
        }
        //Ignore the below override if you're not using any AUTHORIZATION
        @Override
        public Map<String, String> getHeaders () {
            Map<String, String> params = new HashMap<> ();
            params.put ( "authorization", "YOUR AUTH TOKEN" );
            return params;
        }
    };
    volleyMultipartRequest.setRetryPolicy ( new DefaultRetryPolicy (
            100000,
            DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT ) );
    Volley.newRequestQueue ( context ).add ( volleyMultipartRequest );
}

/**
 * This method is used to display response message
 * 
 * @param response
 */
private void showSuccessMessage ( NetworkResponse response ) {
    Log.d ( "LOG", "Response from server: " + response.toString () );
}

/**
 * This method is used to display error message
 * 
 * @param volleyError
 */
private void showErrorMessage ( VolleyError volleyError ) {
    Log.d ( "LOG", "Response from server: " + volleyError.getMessage () );
}

/**
 * This method converts bitmap to byte array
 * 
 * @param bitmap
 * @return byte array
 */
private byte[] getFileDataFromDrawable ( Bitmap bitmap ) {
    ByteArrayOutputStream byteArrayOutputStream = null;
    try {
        byteArrayOutputStream = new ByteArrayOutputStream ();
        bitmap.compress ( Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream );
    } catch (Exception ignored) {

    } finally {
        if (byteArrayOutputStream != null) {
            try {
                byteArrayOutputStream.close ();
            } catch (IOException ignore) {
            }
        }
    }
    return (byteArrayOutputStream != null ? byteArrayOutputStream.toByteArray () : null);
}

这是我正在使用的工作代码。希望上面的代码片段对你有帮助。如果我在此答案中遗漏了任何必要的代码片段,请告诉我。我会尝试更新那些