【问题标题】:How do I upload a image to my server with meteor?如何使用流星将图像上传到我的服务器?
【发布时间】:2016-12-21 15:38:32
【问题描述】:

我的申请页面上有一个徽标。

应用程序管理员应该能够通过简单地上传一个新徽标来调整 Web 应用程序中的徽标。实现这一目标的最佳做法是什么?

我将如何处理服务器上的上传。它应该用新标志替换旧标志。名称和位置应保持不变。

这是我的方法:

我使用包UploadFS:

jalik:ufs
jalik:ufs-local
autopublish //it is still on, so the code below works without publish/subscribe I know that I will have to change that.

我的代码:

上传

*.js 服务器和客户端

//Almost Standard initialization - works so far
Logo = new Mongo.Collection('logo');

LogoStore = new UploadFS.store.Local({
    collection: Logo,
    name: 'logo',
    path: '/uploads/logo',
    mode: '0744', // directory permissions
    writeMode: '0744', // file permissions
    filter: new UploadFS.Filter({
        minSize: 1,
        maxSize: 1024 * 1000, // 1MB,
        contentTypes: ['image/*'],
        extensions: ['png']
    })
 });

*.html

//Standard initialization - works so far
<template name="upload">
    <button type="button" name="upload">Select files</button>
</template>

*.js 客户端

//Almost Standard initialization - works so far
Template.upload.events({
    'click button[name=upload]': function (ev) {
        var self = this;

        UploadFS.selectFiles(function (file) {
            // Prepare the file to insert in database, note that we don't provide an URL,
            // it will be set automatically by the uploader when file transfer is complete.
            var logo = {
                name: 'logo.png', //all uploaded images will have the same name
                size: file.size,
                type: file.type,
                            };

            // Create a new Uploader for this file
            var uploader = new UploadFS.Uploader({
                // This is where the uploader will save the file
                store: LogoStore,
                // Optimize speed transfer by increasing/decreasing chunk size automatically
                adaptive: true,
                // Define the upload capacity (if upload speed is 1MB/s, then it will try to maintain upload at 80%, so 800KB/s)
                // (used only if adaptive = true)
                capacity: 0.8, // 80%
                // The size of each chunk sent to the server
                chunkSize: 8 * 1024, // 8k
                // The max chunk size (used only if adaptive = true)
                maxChunkSize: 128 * 1024, // 128k
                // This tells how many tries to do if an error occurs during upload
                maxTries: 5,
                // The File/Blob object containing the data
                data: file,
                // The document to save in the collection
                file: logo,
                // The error callback
                onError: function (err) {
                    console.error(err);
                },
                onAbort: function (file) {
                    console.log(file.name + ' upload has been aborted');
                },
                onComplete: function (file) {
                    console.log(file.name + ' has been uploaded');
                },
                onCreate: function (file) {
                    console.log(file.name + ' has been created with ID ' + file._id);
                },
                onProgress: function (file, progress) {
                    console.log(file.name + ' ' + (progress*100) + '% uploaded');
                },
                onStart: function (file) {
                    console.log(file.name + ' started');
                },
                onStop: function (file) {
                    console.log(file.name + ' stopped');
                }
            });

            // Starts the upload
            uploader.start();

            // Stops the upload
            uploader.stop();

            // Abort the upload
            uploader.abort();
        });
    }
});

显示上传的徽标

*.html

<template name="whatever">
<img src="{{logoUrl}}" alt="Logo" >
</template>

*.js 仅限客户端

Template.whatever.helpers({
    logoUrl: function(){
       return Logo.findOne().url;
    }

})

所以如果我理解正确的话,代码所做的就是将 img 上传到服务器上的某个位置。它还将有关该图像的一些信息存储在 Mongo.Collection - Logo 中。

但我不知道这些图像存储在哪里,在哪个文件夹中。它们没有存储在我的默认项目 - 文件夹中。 示例 img 的 url 为:http://localhost:3000/ufs/logo/B4Fv5etkr7xQbvs5v/logo.png。中间那个随机字符串就是那个img的_id。所以我不能使用硬编码的 url 来访问这些图像,因为一旦上传了新的 img,该 url 就会完全改变。

Q1:那么第一个问题是:我可以直接上传到myProject/public/img文件夹吗?这样 img 的 url 将类似于: http://localhost:3000/img/logo.png 然后我只需要替换上传的旧徽标。

现在我必须处理通用 url。因此,接下来,我从 Logo - 集合中选择服务器上现在显示的图像的 url,并将该 url 传递给我的模板到必须放置徽标的位置。这样做的问题是,在加载其他所有内容之后加载了 url,因此在几秒钟内我得到了一个没有 url 的标签。因此,该位置仅在加载 url 之前显示替代文本。太丑了……

Q2:问题是,在加载标签之前,我如何获取 url。这样徽标就会出现在其他所有内容之前/之前,就好像 URL 会提前硬编码一样。

Q3:是否可以在上传时用新上传的徽标替换旧徽标?如何?

Q4:如果我从 Logo - Collection 中删除 img 的条目,图片是否真的从服务器中删除了?还是我必须手动/以其他方式删除它?

【问题讨论】:

  • 另一个问题是关于上传到第三方的几张图片。我想将一张图片上传到我的服务器,最好上传到公共文件夹。
  • 这个问题大约每周被以不同的方式提出一次。此外,您本质上只是要求代码,而不是帮助现有代码。 “我将如何做 X?”形式的问题。不适合 Stackoverflow。新的 Stackoverflow 文档页面将非常适合,但仍在填充中。因此,如果现有答案都不适合您,请展示您尝试过的方法,我们会尽力帮助您。
  • 感谢您向我解释我的问题。我添加了自己的方法,并解释了我目前使用该方法所面临的问题。

标签: meteor


【解决方案1】:

您可以在服务器上发送 base64 编码图像,然后使用 fs 覆盖文件。 喜欢:

客户

readAsDataURL 具有 base64 编码的数据,格式为

data:image/jpeg;base64,/9j/4AAQSkZJRgABA...

所以需要去掉前面的mime类型和编码信息。

contents = contents.split(',')[1];

现在您可以将此 base64 编码数据发送到服务器。

服务器

由于您正在接收 base64 编码数据,您可以将其转换为缓冲区并写入文件:

fs.writeFile(filepath, Buffer(argument,'base64'), err => {
  //
})

如果文件名与另一个文件相同,则它将完全覆盖您的文件。

【讨论】:

  • 谢谢,但我无法让 fs.writeFile 在我的项目中运行,所以我尝试了自己的 UploadFS 方法
  • 你必须像这样定义 fs:var fs = require('fs')
【解决方案2】:

问题 1 的答案: 默认图像将存储在项目中的隐藏文件夹 .meteor/local/build/programs/server/ufs/uploads/

您可以通过“路径”更改目的地,如下代码所示

new UploadFS.store.Local({
  collection: Csvs.collection,
  name: 'csv',
  path: '../../../../../uploads/csv', //here change destination folder stored file
  filter: new UploadFS.Filter({
    maxSize: 1024 * 3000, // 3MB,
    contentTypes: ['text/csv']
  })
});

【讨论】:

    【解决方案3】:

    在 Pankaj Javav 的回答中执行“客户端”步骤时,您可能想要使用我创建的 base64-image-upload 包,因为我遇到了同样的问题。它简化了将任何 base64 字符串上传到服务器的过程,您无需通过这种方式摆脱 MIME 类型。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-24
      • 2021-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-03
      • 2014-12-01
      • 2019-03-04
      相关资源
      最近更新 更多