N
N
NiceScript2019-05-16 06:21:59
Node.js
NiceScript, 2019-05-16 06:21:59

How to organize image loading, previewing, sending and saving on the server in vue.js and node.js?

I use element-io
The task is this:
When uploading new images, you need to make a square thumbnail for the person to indicate it himself, then, when all the pictures also have thumbnails, send them to the server, save them in a folder, write the links to the database.
What is now:


  1. There is el-upload (an input with the file type), when it changes, the 'handleChangeIMG' event is processed, where all files are converted into a DOMString (an object containing a link), by which you can see the uploaded pictures.
    code 1

    Input
    <el-upload
                    id="elImageAddNew"
                    drag
                    action=""
                    :auto-upload="false"
                    :on-success="ElImageSuccess"
                    :before-upload="beforeElImageUpload"
                    :show-file-list="false"
                    :on-change="handleChangeIMG"
                    multiple
                    :file-list="ElImageForm.preImagesArray"
                    class="dialog-add-image-content">
                    <i class="el-icon-upload"></i>
                    <div class="el-upload__text">Перенесите файлы или  <em>нажмите для загрузки</em></div>
                    <p>JPG, GIF или PNG.</p>
                </el-upload>

    input change handler
    handleChangeIMG (file, fileList) {
            console.log('handleChange', file, fileList)
            this.ElImageForm.preImagesArray.push(URL.createObjectURL(file.raw))
          }



  2. When the first stage is done, a modal window opens, it contains a slider from the this.ElImageForm.preImagesArray array of images loaded in 1 paragraph. Here we use VueCropper to select the thumbnail. As a result, we have an array of objects, in each blob object there are links to the full version of the picture and a thumbnail.
    I send it to the server.
    code2

    Функция добавления выбранной миниатюры, и запись объекта в итоговый массив
    this.$refs.cropper[0].getCropBlob(data => {
    // делаем изображения из зоны выбора миниатюры
                let imgMini = window.URL.createObjectURL(data)
    //создаём объект для добавления в итоговый массив
                let ob = {
                  img: that.ElImageForm.preImagesArray[index],
                  img_mini: imgMini
                }
    // Добавляем в итоговый массив
                that.ElImageForm.el_src.push(ob)
    // Если последняя миниатюра, то надо отправить на сервер
                if (!hasIndex) {
                  that.ElImageSendAddImages()
                }
              })

    Отправка происходит так
    Api().post('settings', params)
    params - это итоговый массив, и путь обработчика для node js


  3. The server identifies the request, we understand that action === "UPDATE", that the request type is 'image', how to save the data in the database, there are no problems.
    I can not figure out how to save pictures in a folder of some kind.
    code 3
    // feed - это переданный params
    if (feed.value_type === 'image') {
                        // save file
    
                        // save in db
                        if (Array.isArray(feed.new_value)) {
          ... тут всё отрабатывает нормально
          }
                    }



I don’t know, maybe the error is that I’m trying to transfer blob files, in general I won’t guess. It is necessary to save the files on the server, and links to them in the database.
Please help.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
Denis Bazarnov, 2019-05-16
@bazden

I'll clarify the question (perhaps there is an answer in it): are you asking for a "piece of code" to save files in the folder ?

K
kn1ght_t, 2019-05-16
@kn1ght_t

more or less like this:

const receiveFile = (filepath, req, res) => {
  const wstream = fs.createWriteStream(filepath, {flags: 'wx'});

  req
    .pipe(wstream)
    .on('error', (e) => {
      if (e.code === 'EEXIST') {
        res.statusCode = 409;
        res.end('File Already Exists');
        return;
      }

      res.statusCode = 500;
      res.end('Internal Server Error');
    })
    .on('close', () => {
      res.statusCode = 201;
      res.end('File Created');
    });

  res.on('close', () => {
    if (res.finished) return;
    fs.unlink(filepath, (err) => {});
  });
};

G
genius_spirit, 2019-05-16
@genius_spirit

try via multer ( https://github.com/expressjs/multer). I save files in /uploads and put their names in the database

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question