【问题标题】:Image uploading Android + Sails.js图片上传 Android + Sails.js
【发布时间】:2016-02-16 08:23:17
【问题描述】:

有哪些可能的方式/库可用于将图像从 android 应用程序上传到sails.js Node.js 服务器?

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

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

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

【问题讨论】:

    标签: android node.js sails.js


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      对于后端级别,请在您的 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;
      
              }
          });
      },
      

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

           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。

      【讨论】:

        【解决方案3】:

        Sails.js 后端文件上传代码和文件将上传到 assets/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/

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2012-03-07
          • 2015-03-06
          • 1970-01-01
          • 2012-01-25
          • 2012-04-03
          • 2014-04-27
          • 2011-12-22
          相关资源
          最近更新 更多