【问题标题】:Clear form after submit image in Meteor在 Meteor 中提交图像后清除表单
【发布时间】:2017-10-10 06:13:09
【问题描述】:

我在我的 Meteor 应用程序中使用 CFS 上传文件,几乎一切正常,除了因为当我尝试上传另一张图片时,我在表单中看到了我之前发送的图片,所以我需要在提交后清除该表单图片。我试过 .reset 但它不起作用。这是我现在的代码。感谢您的帮助。

NewImage.html

<template name="newImage">
    <div align="center">
      <form align="center">
        <div>
          <div>
            <span class="btn btn-success btn-file">
              <input type="file" accept=".gif,.jpg,.png" class="myFileInputimagepub" id="image"/>
            </span>
          </div>
          <div>
            <img src="{{currentUser.profile.image}}" alt="Image" width="60px" height="60px" class="img-circle avatar-upload" value=''/>
          </div>
        </div>
      </form>
    </div>
  </template>

NewImage.js

import './newImage.html';

Template.NewImage.events({
  'change .myFileInputimagepub':function(evt,tmpl){
    FS.Utility.eachFile(event,function(file){
      fileImagespub.insert(file,function(err,fileObj){
        if(!err){
          var userId = Meteor.userId();
          var imageurl = {
            'profile.image':'/cfs/files/fileimages/' + fileObj._id
          };
          setTimeout(function(){
            Meteor.users.update(userId,{$set:imageurl});
          },2000);
        }
      })
    })
  },

  'submit form':function(event,template){
    event.preventDefault();
    template.find("form").reset();
  }
});

【问题讨论】:

  • (1) 是贴在使用&lt;img src="{{currentUser.profile.image}}"... 渲染的图像周围的图像(2) 当用户的个人资料只能有一个图像时,为什么允许删除多个图像(3)为什么setTimeout 更新用户对象? (4) 渲染的图像不是输入元素所以不能“重置”

标签: javascript jquery meteor


【解决方案1】:

如果有问题的图像是类.img-circle 的图像,则问题在于它的src 属性是动态提供的。目前是currentUser.profile.image。这不会通过重置表单并手动清除图像的src 值来清除,这将与框架发生冲突。

选项 1(不理想):

如果您不想保留图像,请通过运行以下命令取消设置文件上传后所做的数据库更改:

Meteor.users.update(userId, { $set: { 'profile.image': null }});

这并不理想,因为它使您能够使用可能长期不需要的图像继续修改数据库。

此外,我假设您当前正在使用 autopublish/insecure 软件包。您需要在公开您的应用之前删除这些,因为它们允许任何用户无限制地更改数据库。

选项 2:

您可以将'change .myFileInputimagepub' 事件的返回值保存为ReactiveVar,然后仅在用户提交表单时实际运行Meteor.users.update(最好在服务器上使用Method)。那时你可以清除反应变量。

使用 ReactiveVar 将允许您通过帮助程序将保存的 URL 提供给 src 属性,然后在您希望清除表单时更改 ReactiveVar 的值。

这里有一个操作 ReactiveVars 的简单示例:https://gist.github.com/ahoereth/a75d2d6528b1844ad503

【讨论】:

  • 谢谢多姆。第一个选项不起作用,但现在我正在尝试使用第二个选项,即 Reactive Var 来完成此操作。
  • 膨胀。这是一个更好的方法。如果您在使用 ReactiveVar 时遇到问题,请发布源代码。
猜你喜欢
  • 2018-06-04
  • 2023-03-22
  • 1970-01-01
  • 2013-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-12
  • 1970-01-01
相关资源
最近更新 更多