[在Android中使用凌空图片上传到node.js后端

问题描述 投票:2回答:1

[试图在android和node.js后端中使用凌空上传图像。但是当我从后端记录文件时,它是未定义的。该应用程序也停止工作,并立即关闭。我该如何解决并将图片上传到后端?提前致谢。是Android的新手。

这是后端

 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);
}
android android-volley nodes image-uploading multer
1个回答
0
投票

我已经实现了文件上传,但是您可以通过调整代码来将其用于图像上传

我已经使用了以下依赖项

 implementation 'net.gotev:uploadservice:2.1'

现在我们开始选择要上传的文件或图像

 public void launchIntent()

{

    Intent chooseintent = new Intent();

//如果要上传图像,请指定为“图像/ *”

    chooseintent.setType("application/*");

    chooseintent.setAction(Intent.ACTION_GET_CONTENT);



        startActivityForResult(Intent.createChooser(chooseintent, "Select file"), Constants.CHOOSE_FILE_STAFF);



}

@Override

public void onActivityResult(int requestCode,int resultCode,Intent data)

{

    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == Constants.CHOOSE_FILE_STAFF && resultCode == RESULT_OK && data != null && data.getData() != null) {

        stafffilePath = data.getData();

        uploadFile(stafffilePath,"staff");

    }



}
 public void uploadFile(Uri path,String type)

{

    String fullpath = FilePath.getPath(UploadActivity.this,path);





    if (fullpath == null) {



        Toast.makeText(this, "Please move your  file in the internal storage and retry", Toast.LENGTH_LONG).show();

    }

    else

    {

        try {

            String uploadId = UUID.randomUUID().toString();

            singleUploadBroadcastReceiver.setDelegate(UploadActivity.this);

            singleUploadBroadcastReceiver.setUploadID(uploadId);

//在这里,我从路径中获取文件名以便检查文件上传

            String fpath[] = fullpath.split("/");

            String exactfilename = fpath[fpath.length-1];

            String efilename[] = exactfilename.split("\\.");

            String ext = efilename[efilename.length-1];

//在这里,我正在尝试上传excel文件,以便iam检查该文件是否为excel

            if(ext.equals("xls") || ext.equals("xlt") || ext.equals("xlm") || ext.equals("xlsx") || ext.equals("xlsm") || ext.equals("xltm") || ext.equals("xlsb") || ext.equals("xla") || ext.equals("xlam") || ext.equals("xll") ||ext.equals("xlw")) {



                //Creating a multi-part request



                new MultipartUploadRequest(this, uploadId, Constants.UPLOAD_FILE)

                        .addFileToUpload(fullpath, "filedata") //Adding file

                        .addParameter("name", type)

                        .addParameter("email", email)//Adding text parameter to the request

                        .setMaxRetries(2)

                        .startUpload(); //Starting the upload

            }

            else

            {



                AlertDialog.Builder builder = new AlertDialog.Builder(UploadActivity.this);

                builder.setMessage("Please upload a Excel file").setPositiveButton("ok",null).create().show();



            }



        } catch (Exception exc) {

            Toast.makeText(this, exc.getMessage(), Toast.LENGTH_SHORT).show();

        }

    }

}

有关更多信息,请单击here

© www.soinside.com 2019 - 2024. All rights reserved.