B
B
black_eagle_012020-12-13 15:33:49
JavaScript
black_eagle_01, 2020-12-13 15:33:49

Sending a photo from the site to the server. How to implement?

Hello, I'm trying to implement the following:
1) A user uploads a photo to the site
2) The photo is sent to my server
3) I save the photo for later use

How can this even be implemented? There are a lot of articles on the Internet, but everything does not work ...
Server on node.js.

People who write something like: throw a picture in a post request, catch it on the server, save it. Please go to ***

Thanks in advance =)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Y
Yuriy Vorobyov, 2020-12-13
@black_eagle_01

Use this server side library, it's the easiest and most efficient option.
The result will be something like this:

const multer = require('multer');

const store = multer.diskStorage({
  destination(req, file, cb) {
    cb(null, './src/public/images'); // ваша папка для файлов на сервере
  },
  filename(req, file, cb) {
    cb(null, Date.now() + '_' + file.originalname);
  },
});

const upload = multer({ storage: store }).single('file'); // загрузка одного файла
const uploadMany = multer({ storage: store }).array('files'); // загрузка массива файлов

router.put('/test', upload, (req, res, next) => {
 req.body.file // файл 
});
router.put('/test', uploadMany, (req, res, next) => {
 req.body.files // массив файлов
});

On the client, use form-data:
const formdata = new FormData();
formdata.append("file", fileInput.files[0], "/C:/file-path/file.png"); // если файл один 

formdata.append("files", fileInput.files[0], "C:/file-path/file.png"); // если файлов много
formdata.append("files", fileInput.files[0], "C:/file-path/file.png"); // если файлов много

const requestOptions = {
  method: 'POST',
  body: formdata,
  redirect: 'follow'
};

fetch("url/test", requestOptions)
  .then(response => response.text())
  .then(result => console.log(result))
  .catch(error => console.log('error', error));

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question