图片上传Android + Sails.js

问题描述 投票:0回答:3

有什么可能的方式/库可以将图像从android应用上传到sails.js Node.js服务器?

我碰到的一种实现方法是从应用程序发送Base64编码的位图图像字符串并将其保存到数据库,但这似乎是处理多个大尺寸图像的低效率方法,因为Base64编码的字符串比原始字符串大33%尺寸。

另一种方法是将图像作为多部分表单数据发送,但是我找不到很好的例子。 请提供示例,演示如何从应用发送图像并在服务器端处理图像(node.js / sails.js)

是否有其他推荐的库可用于处理android中的图片上传?

android node.js sails.js
3个回答
0
投票

我使用Multer通过多部分表单数据处理文件上传。

开箱即用的它可以做内存和磁盘存储。 通过使用插件模块,您可以使用Multer将文件直接发送到S3或其他存储提供商。


0
投票

对于后端级别,请在SailsJS应用程序中使用以下代码:

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;

        }
    });
},

并且您需要使用多部分请求发送文件。 我正在使用改造库。 这是android代码:

     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");
            }
        });

这会将图像上传到S3-Bucket。


0
投票

Sails.js后端文件上传代码和文件将上传到asset / images文件夹中

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代码:

    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();
            }
        });
    }
});

对于Android代码,您可以参考

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

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