javascript - 使用 vue 公式上传多张图片
问题描述
我有这个 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制定uploadfile函数
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:无法读取未定义的属性“长度”
这意味着property_files
未定义对象,并且您正在尝试访问不存在的东西的属性。正确的对象名称是files
.
.array(字段名[, maxCount])
接受一个文件数组,所有文件的名称都为 fieldname。如果上传的文件超过 maxCount,则可选择错误输出。文件数组将存储在req.files中。
推荐阅读
- javascript - 如何在 QML Text 上的特定单词上添加颜色
- android - 在科尔多瓦使用相机拍摄的降级图像
- django - DRF 将 OneToOneField 设置为当前登录的用户
- nginx - Nginx:是什么导致了这个 301 重定向?
- terraform - 在 terraform 中构建输出地图
- latex - Latex 模板 - 编译
- javascript - 如何通过使用循环和插入变量来解析 json 对象?
- php - Woocommerce,我需要获取 url,所以我可以从那里获取产品 ID
- python - 异步函数完成后的 Python 调用回调
- swift - 通过后退按钮将变量传递给其他视图控制器