node.js'de bir görüntü dosyası nasıl yüklenir?

Sep 25 2020
 var title="this is title";
  var content="this is content";
  const config = { headers: {'Accept': 'application/json', 'Content-Type': 'multipart/form-data' } };
  const form = new FormData()
  let file =event.target.files[0]
  form.append('file', file)
 form.append('title', title)
   form.append('content', content)`enter code here`
Axios.post("http://localhost:3001/article/get/123", form,config ).then((res)=>{
     console.log(res.data)
   })

Yanıtlar

1 NileshSolanki Sep 25 2020 at 17:54

düğümde görüntü veya herhangi bir şey yüklemek için multer kullandım.

Ara yazılım olarak kullandığım yükleme kodu aşağıdadır.

const util = require("util");
const path = require("path");
const multer = require("multer");

const storage = multer.diskStorage({ 
    destination: function (req, file, cb) {
        cb(null, "./Uploads") // folder path where to upload
    }, 
    filename: function (req, file, cb) { 
      cb(null, file.originalname + "-" + Date.now() + path.extname(file.originalname))
    } 
  });

const maxSize = 1 * 20000 * 20000; // file size validation

const uploadFiles = multer({ storage: storage, limits: { fileSize: maxSize } }).array("myfiles", 10); // key name should be myfiles in postman while upload

const uploadFilesMiddleware = util.promisify(uploadFiles);

module.exports = uploadFilesMiddleware;

Aşağıda, yükleme ve dosya kontrolü için denetleyicide oluşturduğum işlev var.

fileUpload = async (req, res) => {
  try {
        let userCode = req.headers.user_code;
        await upload(req, res);
        if (req.files.length <= 0) {
            return res.status(httpStatusCode.OK).send(responseGenerators({}, httpStatusCode.OK, 'Kindly select a file to upload..!!', true));
        }
        let response = [];
        for (const element of req.files) {
            let data =  await service.addFileData(element, userCode);
            response.push(data); // for file path to be stored in database
        }
        if (response && response.length > 0) {
            return res.status(httpStatusCode.OK).send(responseGenerators(response, httpStatusCode.OK, 'File uploaded sucessfully..!!', false));
        } else {
            return res.status(httpStatusCode.OK).send(responseGenerators({}, httpStatusCode.OK, 'Failed to upload file kindly try later..!!', true));
        }
      } catch (error) {
            logger.warn(`Error while fetch post data. Error: %j %s`, error, error)
            return res.status(httpStatusCode.INTERNAL_SERVER_ERROR).send(responseGenerators({}, httpStatusCode.INTERNAL_SERVER_ERROR, 'Error while uploading file data', true))
        }
    }

ve rota böyle gidecek.

router.post('/upload/file', fileUploadController.fileUpload);

Ayrıca, ara yazılımdaki gibi dosya yüklerken postacıda da aynı adı koruduğunuzdan emin olun.

omair Sep 25 2020 at 17:29

Yukarıdaki kod react.js içindedir. Aynı işi node.js'de yapmak istiyorum ve dosya ortak klasörden yüklenecek. ana sorun, ön uç event.target.files [0] 'da olduğu gibi resim dosyasının nasıl yükleneceğidir