Image uploading Android + Sails.js

那年仲夏 提交于 2019-12-12 02:39:15

问题


What are the possible ways/libraries available to upload images from android app to sails.js Node.js server?

One way that I came across to achieve this is sending Base64 encoded Bitmap image string from the app and saving it to the database, but this seems to be an inefficient way to handle multiple big size images as Base64 encoded string is 33% larger than raw size.

Another way is to send images as multipart form data, but I couldn't found good examples on this. Please, provide examples which demonstrate how to send images from app and handle it at serverside (node.js/sails.js)

Are there any other recommended libraries available to handle image uploading in android?


回答1:


I use Multer to handle file uploads via multipart form data.

Out of the box it can do memory and disk storage. By using plugin modules you can use Multer to send files direct to S3 or other storage providers.




回答2:


For backend level, use this piece of code in your SailsJS application:

uploadPhoto: function (req, res) {      
    req.file('photo').upload({
        adapter: require('skipper-s3'),
        key: S3_KEY,
        secret: S3_SECRET,
        bucket: IMAGE_BUCKET_NAME,
        dirname: DIRECTORY_NAME,  
        region: S3_REGION
    }, function (err, uploaded) {
        if(err) {
            //Image not uploaded
            //Returned with error
        } else if(uploaded.length == 0) {
            //Image not uploaded
        } else {

            //Image uploaded

            //Returned Image Path
            var imagePath = uploaded[0].extra.Location;

        }
    });
},

And you need to send the file using multipart request. I am doing it with retrofit library. Here is the android code:

     1. Create Multipart RequestBody Object 


        RequestBody file =
                    RequestBody.create(MediaType.parse("multipart/form-data"), photo); //photo is of type "File"


    2. Handling RequestBody in Interface

        @Multipart
        @POST("api/uploadphoto")
        Call<ResponseBody> uploadPhoto(@Part("photo\"; filename=\"pp\"") RequestBody file);

    3. Then initiating the call to server

    call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Response<ResponseBody> response, Retrofit retrofit) {
                 Log.e("RESPONSE", response.body());
             }   
            }
            @Override
            public void onFailure(Throwable t) {
                Log.e("UploadPhoto", "failed");
            }
        });

That will upload the image to S3-Bucket.




回答3:


Sails.js Backend file upload code and file will be uploaded in assets/images folder

upload: function (req, res) {
        if (req.method === 'GET')
            return res.json({
                'status': 'GET not allowed'
            });
        //  Call to /upload via GET is error

        var data = req.file('uploadFile');

        data.upload({
            dirname: '../../assets/images'
        }, function onUploadComplete(err, files) {
            // Earlier it was ./assets/images .. Changed to ../../assets/images
            //  Files will be uploaded to ./assets/images
            // Access it via localhost:1337/images/file-name
            console.log(files);
            if (err) {
                console.log(err);
                return res.json(500, err);
            } else if (files.length === 0) {
                // proceed without files
                res.notFound({
                    status: 'Unsucess',
                    response: 'File not Uploaded'
                });
            } else {
                //  handle uploaded file
                res.json({
                    status: 200,
                    file: files
                });
            }
        });
    }

Android Code :-

    RequestBody requestBody = new MultipartBody.Builder()  
            .setType(MultipartBody.FORM)
            .addFormDataPart("fileUploadType", "1")
            .addFormDataPart("miniType", contentType)
            .addFormDataPart("ext", file.getAbsolutePath().substring(file.getAbsolutePath().lastIndexOf(".")))
            .addFormDataPart("fileTypeName", "img")
            .addFormDataPart("clientFilePath", selectedImageUri.getPath())
            .addFormDataPart("filedata", filename + ".png", fileBody)
            .build();

    Request request = new Request.Builder()
                .url(API_URL)
                .post(requestBody)
                .build();


OkHttpClient okHttpClient = new OkHttpClient();  
okHttpClient.newCall(request).enqueue(new Callback() {  
    @Override
    public void onFailure(Call call, final IOException e) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                et_response.setText(e.getMessage());
                Toast.makeText(MainActivity.this, "nah", Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public void onResponse(Call call, final Response response) throws IOException {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                try {
                    et_response.setText(response.body().string());
                } catch (IOException e) {
                    e.printStackTrace();
                }
                Toast.makeText(MainActivity.this, "response: " + response, Toast.LENGTH_LONG).show();
            }
        });
    }
});

For Android Code You can Refer to

http://blog.aimanbaharum.com/2016/03/26/android-image-multi-part-upload/



来源:https://stackoverflow.com/questions/35427284/image-uploading-android-sails-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!