image upload with media content

Asked

Viewed 1,366 times

2

How do I upload an image to meteor? I followed this tutorial here but it didn’t work very well. The image is apparently saved, because I checked on Collection and there is a record there, but I can’t even list and much less is created a directory or something like that within my project.

I also saw that in this tutorial when he creates the event is created a variable where is picking up the user id, so I can display the image I need to save the url in another collection?

2 answers

1

  • Welcome to the SO Pt community. It would be helpful if you put in the code and not just links, if for some reason the link goes offline your answer will become useless.

0

The answer given by @altemberg-Andrade is more comprehensive, but if you don’t need so much and something simpler, see this example:

/client/main.html

<body>
  <form id="formSubmit" method="post">
    <input type="file" id="arquivo" name="arquivo" />
    <input type="submit" />
  </form>
  <a href="/upload/">ver uploads</a>
</body>

/client/main.js

import('meteor/meteor').then(({ Meteor }) => {
  formSubmit = document.getElementById('formSubmit')
  formSubmit.addEventListener('submit', (evt) => {
    evt.preventDefault()
    let file = document.querySelector('#arquivo').files[0];
    let reader = new FileReader();

    reader.onloadend = function () {
      let buffer = new Uint8Array(reader.result)
      let { type, name } = file
      Meteor.call('upload', { name, type, buffer }, (err, res) => {
        if(err) throw err
        alert(`sucesso! ${res}`)
      });
    };
    reader.readAsArrayBuffer(file)
  });
});

/server/main.js

import { Meteor } from 'meteor/meteor';
import { Mongo } from 'meteor/mongo';
import { WebApp } from 'meteor/webapp';

const collUpload = new Mongo.Collection('upload')

const uploadPath = '/upload/'

WebApp.connectHandlers.use(uploadPath, (req, res, next) => {
  //console.log(req._parsedUrl)
  let file_id = req._parsedUrl.pathname.replace(uploadPath, '')
  let arquivo = collUpload.findOne(file_id)
  if(!arquivo){
    let arqs = collUpload.find().fetch().map((arq) => {
      return {
        _id: arq._id,
        name: arq.name
      }
    })
    res.writeHead(404);
    res.end(JSON.stringify(arqs, null, 2))
  } else {
    res.writeHead(200, {
      'Content-Type': arquivo.type,
      // use attachment para forçar o download
      'Content-Disposition': `inline; filename=${arquivo.name}`
    });
    res.end(Buffer.from(arquivo.buffer));
  }
});

Meteor.methods({
  upload: function(data){
    return collUpload.insert(data)
  }
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.