首页 \ 问答 \ js.writeFile没有正确编写Blob(js.writeFile not writing Blob correctly)

js.writeFile没有正确编写Blob(js.writeFile not writing Blob correctly)

我有一个Angular服务,具有写文件的功能。 该功能可以在Ionic或Electron平台上运行。 对于Ionic,它使用$ cordovaFile进行文件操作,而对于Electron,它使用节点fs库。

功能如下:

writeFile(filename: string, dirname: string, data: string | Blob, replace?: boolean): ngCordova.IFilePromise<ProgressEvent> {
    if (this.isElectron) {
        let promiseObj = this.$q.defer();
        if (replace) {
            try {
                fs.unlinkSync('./' + dirname + '/' + filename);
            }
            catch (err) {
                //err
            }
        }
        fs.writeFile('./' + dirname + '/' + filename, data, 'binary', () => {
            promiseObj.resolve(true);
        });

        return promiseObj.promise;
    }
    else {
        return this.$cordovaFile.writeFile(cordova.file.dataDirectory + dirname, filename, data, replace);
    }
};

使用Ionic平台时,该功能正常,下载的文件被正确写出。 但是,当使用Electron平台时,所有下载的文件都包含字符串[object Blob]

使用fs将Blob写入文件的正确方法是什么?

更多信息

数据最初在JSON消息中作为base64下载,但我们随后使用它

let fileBlob = this.stringUtilityService.b64ToBlob(dataObj.Data[i].FileContents, 'image/png');

    this.fileSystemService.writeFile(dataObj.Data[i].FileName, 'icons', fileBlob);

额外的信息

这是b64ToBlob()函数,虽然据我所知,这个函数工作正常并正确返回一个blob,Ionic应用程序正确保存并可以显示。

b64ToBlob(b64Data: string, contentType: string): any {
        let sliceSize = 512;

        let byteCharacters = atob(b64Data);
        let byteArrays = [];

        for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
            let slice = byteCharacters.slice(offset, offset + sliceSize);

            let byteNumbers = new Array(slice.length);
            for (let i = 0; i < slice.length; i++) {
                byteNumbers[i] = slice.charCodeAt(i);
            }

            let byteArray = new Uint8Array(byteNumbers);

            byteArrays.push(byteArray);
        }

        let blob = new Blob(byteArrays, { type: contentType });
        return blob;
    }

I have an Angular service with a function for writing files away. The function can work on either an Ionic or Electron platform. For Ionic, it uses $cordovaFile for file actions and for Electron it uses the node fs library.

The function is as follows:

writeFile(filename: string, dirname: string, data: string | Blob, replace?: boolean): ngCordova.IFilePromise<ProgressEvent> {
    if (this.isElectron) {
        let promiseObj = this.$q.defer();
        if (replace) {
            try {
                fs.unlinkSync('./' + dirname + '/' + filename);
            }
            catch (err) {
                //err
            }
        }
        fs.writeFile('./' + dirname + '/' + filename, data, 'binary', () => {
            promiseObj.resolve(true);
        });

        return promiseObj.promise;
    }
    else {
        return this.$cordovaFile.writeFile(cordova.file.dataDirectory + dirname, filename, data, replace);
    }
};

When the Ionic platform is used, the function works fine and the downloaded files are written away correctly. However, when the Electron platform is used, all the downloaded files contain is the string [object Blob].

What is the correct way to write Blobs to files using fs?

MORE INFO

The data originally comes down as base64 in a JSON message but we then do this with it

let fileBlob = this.stringUtilityService.b64ToBlob(dataObj.Data[i].FileContents, 'image/png');

    this.fileSystemService.writeFile(dataObj.Data[i].FileName, 'icons', fileBlob);

EXTRA MORE INFO

Here is the b64ToBlob() function, although as far as i can tell this function works fine and correctly returns a blob which the Ionic app correctly saves away and can display.

b64ToBlob(b64Data: string, contentType: string): any {
        let sliceSize = 512;

        let byteCharacters = atob(b64Data);
        let byteArrays = [];

        for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
            let slice = byteCharacters.slice(offset, offset + sliceSize);

            let byteNumbers = new Array(slice.length);
            for (let i = 0; i < slice.length; i++) {
                byteNumbers[i] = slice.charCodeAt(i);
            }

            let byteArray = new Uint8Array(byteNumbers);

            byteArrays.push(byteArray);
        }

        let blob = new Blob(byteArrays, { type: contentType });
        return blob;
    }

原文:https://stackoverflow.com/questions/41808702
更新时间:2022-10-12 09:10

最满意答案

这是使用pprint漂亮打印的data

{'service_group_stat': {'cur_conns': 71,
                    'cur_reqs': 0,
                    'member_stat_list': [{'cur_conns': 11,
                                          'cur_reqs': 0,
                                          'port': 81,
                                          'req_bytes': 447460215,
                                          'req_pkts': 3134918,
                                          'resp_bytes': 10134966691,
                                          'resp_pkts': 7834233,
                                          'server': 'WWW0006',
                                          'status': 1,
                                          'tot_conns': 52311,
                                          'total_reqs': 0,
                                          'total_reqs_succ': 0},
                                         {'cur_conns': 5,
                                          'cur_reqs': 0,
                                          'port': 81,
                                          'req_bytes': 548725475,
                                          'req_pkts': 3870142,
                                          'resp_bytes': 12396718148,
                                          'resp_pkts': 9572363,
                                          'server': 'WWW0005',
                                          'status': 1,
                                          'tot_conns': 61464,
                                          'total_reqs': 0,
                                          'total_reqs_succ': 0},
                                         {'cur_conns': 15,
                                          'cur_reqs': 0,
                                          'port': 81,
                                          'req_bytes': 711362272,
                                          'req_pkts': 5051483,
                                          'resp_bytes': 15868605964,
                                          'resp_pkts': 12282023,
                                          'server': 'WWW0004',
                                          'status': 1,
                                          'tot_conns': 80898,
                                          'total_reqs': 0,
                                          'total_reqs_succ': 0},
                                         {'cur_conns': 23,
                                          'cur_reqs': 0,
                                          'port': 81,
                                          'req_bytes': 92624447982,
                                          'req_pkts': 575717964,
                                          'resp_bytes': 1832290858664,
                                          'resp_pkts': 1417192127,
                                          'server': 'WWW0003',
                                          'status': 1,
                                          'tot_conns': 7265009,
                                          'total_reqs': 0,
                                          'total_reqs_succ': 0},
                                         {'cur_conns': 14,
                                          'cur_reqs': 0,
                                          'port': 81,
                                          'req_bytes': 97240370978,
                                          'req_pkts': 634692796,
                                          'resp_bytes': 1909851841929,
                                          'resp_pkts': 1479318756,
                                          'server': 'WWW0002',
                                          'status': 1,
                                          'tot_conns': 7130096,
                                          'total_reqs': 0,
                                          'total_reqs_succ': 0},
                                         {'cur_conns': 3,
                                          'cur_reqs': 0,
                                          'port': 81,
                                          'req_bytes': 93596613191,
                                          'req_pkts': 586137971,
                                          'resp_bytes': 1839297678302,
                                          'resp_pkts': 1422848182,
                                          'server': 'WWW0001',
                                          'status': 1,
                                          'tot_conns': 7172117,
                                          'total_reqs': 0,
                                          'total_reqs_succ': 0}],
                    'name': 'SG_ACCOUNT.BUSINESS.COM_443',
                    'protocol': 2,
                    'req_bytes': 285168980113,
                    'req_pkts': 1808605274,
                    'resp_bytes': 5619840669698,
                    'resp_pkts': 4349047684,
                    'status': 3,
                    'tot_conns': 21761895,
                    'total_reqs': 0,
                    'total_reqs_succ': 0}}

使用此信息,我们现在可以处理它。 对于member_stat_list每个服务器,我们可以按您所说的格式打印数据:

for server in data["service_group_stat"][["member_stat_list"]:
    print("Server:".ljust(20," ")+server["server"].ljust(32," ")+"Server Connections:".ljust(24," ")+str(server["cur_conns"]))

Here is data pretty-printed using pprint:

{'service_group_stat': {'cur_conns': 71,
                    'cur_reqs': 0,
                    'member_stat_list': [{'cur_conns': 11,
                                          'cur_reqs': 0,
                                          'port': 81,
                                          'req_bytes': 447460215,
                                          'req_pkts': 3134918,
                                          'resp_bytes': 10134966691,
                                          'resp_pkts': 7834233,
                                          'server': 'WWW0006',
                                          'status': 1,
                                          'tot_conns': 52311,
                                          'total_reqs': 0,
                                          'total_reqs_succ': 0},
                                         {'cur_conns': 5,
                                          'cur_reqs': 0,
                                          'port': 81,
                                          'req_bytes': 548725475,
                                          'req_pkts': 3870142,
                                          'resp_bytes': 12396718148,
                                          'resp_pkts': 9572363,
                                          'server': 'WWW0005',
                                          'status': 1,
                                          'tot_conns': 61464,
                                          'total_reqs': 0,
                                          'total_reqs_succ': 0},
                                         {'cur_conns': 15,
                                          'cur_reqs': 0,
                                          'port': 81,
                                          'req_bytes': 711362272,
                                          'req_pkts': 5051483,
                                          'resp_bytes': 15868605964,
                                          'resp_pkts': 12282023,
                                          'server': 'WWW0004',
                                          'status': 1,
                                          'tot_conns': 80898,
                                          'total_reqs': 0,
                                          'total_reqs_succ': 0},
                                         {'cur_conns': 23,
                                          'cur_reqs': 0,
                                          'port': 81,
                                          'req_bytes': 92624447982,
                                          'req_pkts': 575717964,
                                          'resp_bytes': 1832290858664,
                                          'resp_pkts': 1417192127,
                                          'server': 'WWW0003',
                                          'status': 1,
                                          'tot_conns': 7265009,
                                          'total_reqs': 0,
                                          'total_reqs_succ': 0},
                                         {'cur_conns': 14,
                                          'cur_reqs': 0,
                                          'port': 81,
                                          'req_bytes': 97240370978,
                                          'req_pkts': 634692796,
                                          'resp_bytes': 1909851841929,
                                          'resp_pkts': 1479318756,
                                          'server': 'WWW0002',
                                          'status': 1,
                                          'tot_conns': 7130096,
                                          'total_reqs': 0,
                                          'total_reqs_succ': 0},
                                         {'cur_conns': 3,
                                          'cur_reqs': 0,
                                          'port': 81,
                                          'req_bytes': 93596613191,
                                          'req_pkts': 586137971,
                                          'resp_bytes': 1839297678302,
                                          'resp_pkts': 1422848182,
                                          'server': 'WWW0001',
                                          'status': 1,
                                          'tot_conns': 7172117,
                                          'total_reqs': 0,
                                          'total_reqs_succ': 0}],
                    'name': 'SG_ACCOUNT.BUSINESS.COM_443',
                    'protocol': 2,
                    'req_bytes': 285168980113,
                    'req_pkts': 1808605274,
                    'resp_bytes': 5619840669698,
                    'resp_pkts': 4349047684,
                    'status': 3,
                    'tot_conns': 21761895,
                    'total_reqs': 0,
                    'total_reqs_succ': 0}}

Using this info, we can now process it. For each server in member_stat_list, we can print the data in the format you said like this:

for server in data["service_group_stat"][["member_stat_list"]:
    print("Server:".ljust(20," ")+server["server"].ljust(32," ")+"Server Connections:".ljust(24," ")+str(server["cur_conns"]))

相关问答

更多

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)