簡體   English   中英

使用 vue 公式上傳多張圖片

[英]Uploading multiple images with vue formulate

我有這個 Vue 公式化組件

<FormulateInput
          type="image"
          name="property_files"
          v-model="property_images"
          label="Select an images to upload"
          help="Select a png, jpg,webp or gif to upload."
          validation="mime:image/jpeg,image/png,image/gif,image/webp"
          :uploader="uploadFile"
          multiple
/>

我正在使用將多個圖像上傳到 express js 后端。

這是快速js方法

var express = require('express');
var router = express.Router();
var multer = require('multer');

const DIR = './public/';

const MongoClient = require('mongodb').MongoClient;

const url = 'mongodb://localhost:27017';
const dbName = 'dev';


const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, DIR);
  },
  filename: (req, file, cb) => {
    const fileName = file.originalname.toLowerCase().split(' ').join('-');
    cb(null, fileName)
  }
});

var upload = multer({
  storage: storage,
  fileFilter: (req, file, cb) => {
    if (file.mimetype == "image/png" || file.mimetype == "image/jpg" || file.mimetype == "image/jpeg") {
      cb(null, true);
    } else {
      cb(null, false);
      return cb(new Error('Only .png, .jpg and .jpeg format allowed!'));
    }
  }
});

router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});

router.post('/read', upload.array('property_files', 10), (req, res, next) => {
  const reqFiles = []
  const url = req.protocol + '://' + req.get('host')
  for (var i = 0; i < req.property_files.length; i++) {
    reqFiles.push(url + '/public/' + req.property_files[i].filename)
  }
  res.send('happy insert'); 
});

module.exports = router;

這是我的 vue 制定上傳文件 function

    uploadFile: async function (file, progress, error, options) {
    try {
        console.log(file, options);
        const formData = new FormData()
        formData.append('property_files', file)
        const result = await fetch('http://localhost:3000/ca/read', {
            method: 'POST',
            body: formData
        })
        progress(100) // (native fetch doesn’t support progress updates)
        return await result.json()
    } catch (err) {
        error('Unable to upload file')
    }
},

上傳了多張圖片,但不久之后,我收到了這個錯誤

TypeError: Cannot read property 'length' of undefined

在這條線上

for (var i = 0; i < req.property_files.length; i++) {

我想重命名上傳的圖像並刪除圖像名稱上的任何特殊字符,並按照 vue 公式的要求返回所需的格式。

為什么我的代碼會拋出錯誤?

更新

我能夠使用 php 成功上傳

<?php
header('Access-Control-Allow-Origin: *');

header('Access-Control-Allow-Methods: GET, POST');

header("Access-Control-Allow-Headers: X-Requested-With");


$image = '';

if(isset($_FILES['property_files']['name']))
{
 $image_name = $_FILES['property_files']['name'];
 $valid_extensions = array("jpg","jpeg","png");
 $extension = pathinfo($image_name, PATHINFO_EXTENSION);
 if(in_array($extension, $valid_extensions))
 {
  $upload_path = 'uploads/' . uniqid() . '.' . $extension;
  if(move_uploaded_file($_FILES['property_files']['tmp_name'], $upload_path))
  {
   $message = 'Image Uploaded';
   $image = $upload_path;
  }
  else
  {
   $message = 'There is an error while uploading image';
  }
 }
 else
 {
  $message = 'Only .jpg, .jpeg and .png Image allowed to upload';
 }
}
else
{
 $message = 'Select Image';
}
/**
$output = array(
 'message'  => $message,
 'image'   => $image
);
*/
 $output = array(
 'image'   => $image
);
echo json_encode($output);

但我仍然對處理 express js 中的上傳感興趣。

TypeError:無法讀取未定義的屬性“長度”

這意味着未定義 object property_files ,並且您正在嘗試訪問不存在的東西的屬性。 正確的 object 名稱是files

multer API

.array(字段名[, maxCount])

接受一個文件數組,所有文件的名稱都為 fieldname。 如果上傳的文件超過 maxCount,則可選擇錯誤輸出。 文件數組將存儲在req.files中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM