图像上传成功,但它是一个base64字符串,但multer需要一个文件。我怎么能解决这个问题

时间:2017-09-06 10:07:21

标签: android android-volley nodes image-uploading multer

我试图在android和node.js后端使用volley上传图像。图像以base64字符串形式出现,但是multer需要一个文件。我怎么能这样做?我想将图像上传到文件夹并将URL发布到数据库。

这是req.file未定义的后端

 app.post("/upload", multer({storage: storage}).single('bitmap'), (req, res) => {
    // console.log(req.body);
    console.log(req.file);
    console.log('here');
        var db = couchdb.couchConnect('ezymarketplace');
        // req.body['photo_url'] = req.file.filename;
        req.body['type'] = 'feedback';
        var insert = couchdb.couchInsert(db, req.body).then(result => {
            res.send({"result": result[0], "status": result[1].statusCode});

        }).catch(err => {

        });
});

这是主要类,一切都很好

@Override
public void onClick(View v) {
    switch (v.getId()){
        case R.id.buttonChoose:
            showPictureDialog();
            break;


        case R.id.buttonUpload:
            uploadImage();
            break;
    }
}


private void showPictureDialog() {
    AlertDialog.Builder pictureDialog = new AlertDialog.Builder(this);
    pictureDialog.setTitle("Select Action");
    String[] pictureDialogItems = {
            "Select photo from gallery",
            "Capture photo from camera"};
    pictureDialog.setItems(pictureDialogItems,
            new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    switch (which) {
                        case 0:
                            choosePhotoFromGallary();
                            break;
                        case 1:
                            takePhotoFromCamera();
                            break;
                    }
                }
            });
    pictureDialog.show();
}

public void choosePhotoFromGallary() {
    Intent galleryIntent = new Intent(Intent.ACTION_PICK,
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

    startActivityForResult(galleryIntent, GALLERY);
}

private void takePhotoFromCamera() {
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    startActivityForResult(intent, CAMERA);
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {

    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == this.RESULT_CANCELED) {
        return;
    }
    if (requestCode == GALLERY) {
        if (data != null) {
            Uri contentURI = data.getData();
            try {
                 bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), contentURI);
                Log.e("The image", imageToString(bitmap));
                imageview.setImageBitmap(bitmap);


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

    } else if (requestCode == CAMERA) {
        Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
        imageview.setImageBitmap(thumbnail);
        Toast.makeText(MainActivity.this, "Image Saved!", Toast.LENGTH_SHORT).show();
    }
}

public String saveImage(Bitmap myBitmap) {
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    myBitmap.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
    File wallpaperDirectory = new File(
            Environment.getExternalStorageDirectory() + IMAGE_DIRECTORY);
    if (!wallpaperDirectory.exists()) {
        wallpaperDirectory.mkdirs();
    }

    try {
        File f = new File(wallpaperDirectory, Calendar.getInstance()
                .getTimeInMillis() + ".jpg");
        f.createNewFile();
        FileOutputStream fo = new FileOutputStream(f);
        fo.write(bytes.toByteArray());
        MediaScannerConnection.scanFile(this,
                new String[]{f.getPath()},
                new String[]{"image/jpeg"}, null);
        fo.close();
        Log.d("TAG", "File Saved::--->" + f.getAbsolutePath());

        return f.getAbsolutePath();
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    return "";
}

private void uploadImage() {
    final ProgressDialog loading = ProgressDialog.show(this, "Uploading...", "Please wait...", false, false);
    StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_UPLOAD,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String s) {
                    loading.dismiss();
                    Toast.makeText(MainActivity.this, s, Toast.LENGTH_LONG).show();
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {
                    loading.dismiss();

                    Toast.makeText(MainActivity.this, volleyError.getMessage().toString(), Toast.LENGTH_LONG).show();
                }
            }) {
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {

            String image = imageToString(bitmap);



            Map<String, String> params = new Hashtable<String, String>();


            params.put(KEY_IMAGE, image);
            return params;
        }
    };

    RequestQueue requestQueue = Volley.newRequestQueue(this);

    requestQueue.add(stringRequest);
}

private String imageToString(Bitmap bitmap) {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
    byte[] imgBytes = byteArrayOutputStream.toByteArray();
    return Base64.encodeToString(imgBytes, Base64.DEFAULT);
}

0 个答案:

没有答案