简体   繁体   English

使用云代码解析服务器保存 jpg 文件

[英]Saving jpg file with cloud-code Parse-Server

I'm trying to save jpg files with cloud code on parse server ...我正在尝试在解析服务器上使用云代码保存 jpg 文件...

On Android I can do it using this way在 Android 上,我可以使用这种方式

Bitmap bitmap = ((BitmapDrawable) myImageView.getDrawable()).getBitmap();

ByteArrayOutputStream stream = new ByteArrayOutputStream();
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
                    byte [] byteArrayPhotoUpdate = stream.toByteArray();
                    final ParseFile pictureFileParse = new ParseFile( newUserInfo.getObjectId() + ".JPEG",byteArrayPhotoUpdate);

     newUserInfo.put("profile_picture",pictureFileParse);
     newUserInfo.saveInBackground();

But I have no idea how to do this in the cloud code.但我不知道如何在云代码中执行此操作。 I call my cloud code functions like this我这样称呼我的云代码函数

HashMap<String, String> params = new HashMap();

ParseCloud.callFunctionInBackground("myCloudFuncion", params, new FunctionCallback<String>() {
         @Override
          public void done(String aFloat, ParseException e) {

                }
            }); 

but I have no idea how to pass a bitmap in hashmap params.但我不知道如何在 hashmap 参数中传递位图。 I already searched the internet, but nothing that I found in helped, the links that refer to something useful, is already old and outdated, from the epoch of the old parse ...我已经在互联网上搜索过,但我发现的任何内容都没有帮助,链接指向有用的东西,从旧解析的时代开始,已经过时了......

In parse docs I found this解析文档中,我发现了这个

    var base64 = "V29ya2luZyBhdCBQYXJzZSBpcyBncmVhdCE=";
    var file = new Parse.File("myfile.txt", { base64: base64 });

Which made me confused because I do not know if the 2 "base64" parameters refer to variable or base64 type这让我感到困惑,因为我不知道 2 个“base64”参数是指变量还是 base64 类型

Should I convert my bitmap to base64 and send it as parameter to the cloud code?我应该将位图转换为 base64 并将其作为参数发送到云代码吗?

If you have been through this and know how, I will be very happy to know your solution.如果你已经经历过这个并且知道如何,我会很高兴知道你的解决方案。 Thank you!谢谢!

you need convert your image bitmap for base64 like that:您需要像这样将图像位图转换为 base64:

            Bitmap bitmap = ((BitmapDrawable) img.getDrawable()).getBitmap();

            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
            byte [] byteArrayPhotoUpdate = stream.toByteArray();
            String encodedfile = new String(Base64.encodeBase64(byteArrayPhotoUpdate), "UTF-8");

And then, send your string base64 in params, like that:然后,将您的字符串 base64 发送到 params 中,如下所示:

 HashMap<String, String> params = new HashMap();
 params.put("fileInfo",encodedfile);
 ParseCloud.callFunctionInBackground("saveParseUserInfo", params, new FunctionCallback<String>() {
                    @Override
                    public void done(String aFloat, ParseException e) {

                     Log.i("ewaeaweaweaweawe", "done: " + aFloat);
                    }
                });

Now in your cloud code, use that:现在在您的云代码中,使用它:

Parse.Cloud.define("saveParseUserInfo", function(request, response) {
                var userId = request.user.id;
                var base64 = request.params.fileInfo;
                var userClass = Parse.Object.extend("User");
                //create a user object to set ACL
                var userObject = userClass.createWithoutData(userId);

                //create new ParseObject
                var userPublicClass = Parse.Object.extend("userPublic");
                var userPublic = new userPublicClass();
                var aclAction = new Parse.ACL(userObject);
                aclAction.setPublicReadAccess(true);
                userPublic.setACL(aclAction);
                userPublic.set("name", "name random");
                userPublic.set("username", "username_random");
                //Now create a Parse File object
                var file = new Parse.File("photo.jpeg", { base64: base64 });
                //set file object in a colum profile_picture
                userPublic.set("profile_picture",file);
                //save
                userPublic.save(null, { useMasterKey: true,  
                success: function(actionSuccess) {  

                    response.success("saved!!");
                },
                error: function(action, error) {
                    // Execute any logic that should take place if the save fails.
                    // error is a Parse.Error with an error code and message.
                response.error(error.message);
            }
            });






            });     

I hope it's help you.我希望它对你有帮助。

This answer works if you do not wish to use Base64 that requires API 26 and above for android.如果您不希望为 android 使用需要 API 26 及更高版本的 Base64,则此答案有效。

I know João Armando has answered this question, but this is for the benefit of others who, like me, are supporting versions before API 26 for Android.我知道 João Armando 已经回答了这个问题,但这是为了其他人和我一样支持 API 26 之前的 Android 版本的人的利益。

PS The Base64.encodeBase64(...) is deprecated and Base64.getEncoder()... is used now, which requires API 26. PS Base64.encodeBase64(...) 已弃用,现在使用 Base64.getEncoder()...,这需要 API 26。

There are 3 key parts to the solution:解决方案有 3 个关键部分:

  1. Convert your bitmap to byteArray将您的位图转换为 byteArray
  2. Send this byteArray directly as params when calling your cloud function调用云函数时直接将此 byteArray 作为参数发送
  3. Format this byteArray in cloud code itself在云代码本身中格式化这个 byteArray

In Android:在安卓中:

Convert bitmap to byte[]将位图转换为字节[]

Bitmap bitmap = <Your source>;
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();

Send as params when calling cloud function调用云函数时作为参数发送

HashMap<String, Object> params = new HashMap<>();
params.put("imageInByteArray", byteArray);

ParseCloud.callFunctionInBackground("yourCloudFunction", params, new FunctionCallback<Map>() {
  @Override
  public void done(Map object, ParseException e) {
     if(e == null){
       // Success
     } else {
       // Failed
     }
  }
});

In cloud function/code在云函数/代码中

Depends on the version of javascript you use, the codes may differ.取决于您使用的 javascript 版本,代码可能会有所不同。 I am using a backend-as-a-service provider, which has improved from promises-related codes.我正在使用后端即服务提供者,它已从与承诺相关的代码中得到改进。 The logic should still be applicable regardless.无论如何,逻辑应该仍然适用。

Parse.Cloud.define("reportId", async request => {
  // Retrieve and set values from client app
  const imageInByteArray = request.params.imageInByteArray;

  // Format as ParseFile
  var file = new Parse.File("image.png", imageInByteArray);

  // Initialize your class, etc.
  ....

  // Save your object
  await yourImageObject.save(null, {useMasterKey:true});

});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM