Javascript 如何使用Angular7和node.js同时上传图像阵列和缩略图?
我有一个基于Javascript 如何使用Angular7和node.js同时上传图像阵列和缩略图?,javascript,node.js,angular,multer,image-upload,Javascript,Node.js,Angular,Multer,Image Upload,我有一个基于node.js(express)的server-side,其中我有一个api,用于添加BookingItem,在其中我获取预订项目的图像数组 我在服务器端的bookingItem.route.js中这样做 var storage = multer.diskStorage({ destination: function (req, file, cb) { cb(null, 'uploads/item') }, filename: function (req, file, cb) { l
node.js(express)
的server-side
,其中我有一个api
,用于添加BookingItem
,在其中我获取预订项目的图像数组
我在服务器端的bookingItem.route.js中这样做
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'uploads/item')
},
filename: function (req, file, cb) {
let customFileName = crypto.randomBytes(18).toString('hex'),
fileExtension = file.originalname.split('.')[file.originalname.split('.').length - 1] // get file extension from original file name
cb(null, customFileName + '.' + fileExtension)
}
});
var upload = multer({ storage: storage });
router.post("/", log, loggedIn, upload.array("image", 5), addBookingItem);
export async function addBookingItem(req, res) {
let body = parseBody(req)
if (body) {
if (req.files) {
let pictures = []
req.files.forEach(item => {
pictures.push(item.filename)
})
body.picture = pictures
}
if (body.amenityIds) {
let amenityIds = body.amenityIds.split(",")
body.amenityIds = amenityIds
}
body.createdAt = Date.now()
body.updatedAt = Date.now()
let itemObject = new BookingItem(body)
let item = await itemObject.save()
if (item) {
generateResponse(true, "Booking Item" + MESSAGES.ADDED, item, res)
} else {
generateResponse(false, MESSAGES.CANT_ADD, null, res)
}
} else {
generateResponse(false, MESSAGES.COMPLETE_INFO, null, res)
}
}
<input style="display: none" type="file" (change)="onFileChanged($event)" multiple #fileInput>
<button (click)="fileInput.click()" class="btn btn-primary float-left"> Upload Pictures</button>
onFileChanged(event) {
this.selectedPictures = Array.from(event.target.files)
this.data = new FormData()
Array.from(this.selectedPictures).forEach((item: any) => {
this.data.append('image', item)
})
}
addVenue() {
this.spinnerService.show()
if (this.selectedAmenities.length > 0) {
let am = []
this.selectedAmenities.forEach((item: any) => {
am.push(item._id)
})
if (am.length > 0) {
this.amenityIds = am.join(",")
}
}
let tempFor = []
let tempType = []
let tempBookingType = []
this.selectedFor.forEach(item => {
tempFor.push(item.name)
})
this.selectedVenueType.forEach(item => {
tempType.push(item.name)
})
this.selectedBookingType.forEach(item => {
tempBookingType.push(item.name)
})
this.data.append("name", this.addVenueForm.value.name)
this.data.append("checkIn", this.addVenueForm.value.checkIn)
this.data.append("checkOut", this.addVenueForm.value.checkOut)
this.data.append("pricePerNight", this.addVenueForm.value.pricePerNight)
this.data.append("for", tempFor)
this.data.append("bookingType", tempBookingType)
this.data.append("type", tempType)
this.data.append("amenityIds", this.amenityIds)
this.data.append("locationId", this.addVenueForm.value.locationId)
this.appService.addBookingItem(this.data).then((resp: any) => {
this.appService.showSimpleAlert("Venue", resp.message, resp.success ? 'success' : 'error');
if (resp.success) {
this.selectedBookingType = []
this.selectedAmenities = []
this.selectedFor = []
this.selectedVenueType = []
this.selectedPictures = []
this.addVenueForm.reset()
this.spinnerService.hide()
}
})
}
在我的bookingItem.controller.js中,我像这样保存预订项目
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'uploads/item')
},
filename: function (req, file, cb) {
let customFileName = crypto.randomBytes(18).toString('hex'),
fileExtension = file.originalname.split('.')[file.originalname.split('.').length - 1] // get file extension from original file name
cb(null, customFileName + '.' + fileExtension)
}
});
var upload = multer({ storage: storage });
router.post("/", log, loggedIn, upload.array("image", 5), addBookingItem);
export async function addBookingItem(req, res) {
let body = parseBody(req)
if (body) {
if (req.files) {
let pictures = []
req.files.forEach(item => {
pictures.push(item.filename)
})
body.picture = pictures
}
if (body.amenityIds) {
let amenityIds = body.amenityIds.split(",")
body.amenityIds = amenityIds
}
body.createdAt = Date.now()
body.updatedAt = Date.now()
let itemObject = new BookingItem(body)
let item = await itemObject.save()
if (item) {
generateResponse(true, "Booking Item" + MESSAGES.ADDED, item, res)
} else {
generateResponse(false, MESSAGES.CANT_ADD, null, res)
}
} else {
generateResponse(false, MESSAGES.COMPLETE_INFO, null, res)
}
}
<input style="display: none" type="file" (change)="onFileChanged($event)" multiple #fileInput>
<button (click)="fileInput.click()" class="btn btn-primary float-left"> Upload Pictures</button>
onFileChanged(event) {
this.selectedPictures = Array.from(event.target.files)
this.data = new FormData()
Array.from(this.selectedPictures).forEach((item: any) => {
this.data.append('image', item)
})
}
addVenue() {
this.spinnerService.show()
if (this.selectedAmenities.length > 0) {
let am = []
this.selectedAmenities.forEach((item: any) => {
am.push(item._id)
})
if (am.length > 0) {
this.amenityIds = am.join(",")
}
}
let tempFor = []
let tempType = []
let tempBookingType = []
this.selectedFor.forEach(item => {
tempFor.push(item.name)
})
this.selectedVenueType.forEach(item => {
tempType.push(item.name)
})
this.selectedBookingType.forEach(item => {
tempBookingType.push(item.name)
})
this.data.append("name", this.addVenueForm.value.name)
this.data.append("checkIn", this.addVenueForm.value.checkIn)
this.data.append("checkOut", this.addVenueForm.value.checkOut)
this.data.append("pricePerNight", this.addVenueForm.value.pricePerNight)
this.data.append("for", tempFor)
this.data.append("bookingType", tempBookingType)
this.data.append("type", tempType)
this.data.append("amenityIds", this.amenityIds)
this.data.append("locationId", this.addVenueForm.value.locationId)
this.appService.addBookingItem(this.data).then((resp: any) => {
this.appService.showSimpleAlert("Venue", resp.message, resp.success ? 'success' : 'error');
if (resp.success) {
this.selectedBookingType = []
this.selectedAmenities = []
this.selectedFor = []
this.selectedVenueType = []
this.selectedPictures = []
this.addVenueForm.reset()
this.spinnerService.hide()
}
})
}
在client-side
上,我使用angular7
从客户端发送图片,如下所示
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'uploads/item')
},
filename: function (req, file, cb) {
let customFileName = crypto.randomBytes(18).toString('hex'),
fileExtension = file.originalname.split('.')[file.originalname.split('.').length - 1] // get file extension from original file name
cb(null, customFileName + '.' + fileExtension)
}
});
var upload = multer({ storage: storage });
router.post("/", log, loggedIn, upload.array("image", 5), addBookingItem);
export async function addBookingItem(req, res) {
let body = parseBody(req)
if (body) {
if (req.files) {
let pictures = []
req.files.forEach(item => {
pictures.push(item.filename)
})
body.picture = pictures
}
if (body.amenityIds) {
let amenityIds = body.amenityIds.split(",")
body.amenityIds = amenityIds
}
body.createdAt = Date.now()
body.updatedAt = Date.now()
let itemObject = new BookingItem(body)
let item = await itemObject.save()
if (item) {
generateResponse(true, "Booking Item" + MESSAGES.ADDED, item, res)
} else {
generateResponse(false, MESSAGES.CANT_ADD, null, res)
}
} else {
generateResponse(false, MESSAGES.COMPLETE_INFO, null, res)
}
}
<input style="display: none" type="file" (change)="onFileChanged($event)" multiple #fileInput>
<button (click)="fileInput.click()" class="btn btn-primary float-left"> Upload Pictures</button>
onFileChanged(event) {
this.selectedPictures = Array.from(event.target.files)
this.data = new FormData()
Array.from(this.selectedPictures).forEach((item: any) => {
this.data.append('image', item)
})
}
addVenue() {
this.spinnerService.show()
if (this.selectedAmenities.length > 0) {
let am = []
this.selectedAmenities.forEach((item: any) => {
am.push(item._id)
})
if (am.length > 0) {
this.amenityIds = am.join(",")
}
}
let tempFor = []
let tempType = []
let tempBookingType = []
this.selectedFor.forEach(item => {
tempFor.push(item.name)
})
this.selectedVenueType.forEach(item => {
tempType.push(item.name)
})
this.selectedBookingType.forEach(item => {
tempBookingType.push(item.name)
})
this.data.append("name", this.addVenueForm.value.name)
this.data.append("checkIn", this.addVenueForm.value.checkIn)
this.data.append("checkOut", this.addVenueForm.value.checkOut)
this.data.append("pricePerNight", this.addVenueForm.value.pricePerNight)
this.data.append("for", tempFor)
this.data.append("bookingType", tempBookingType)
this.data.append("type", tempType)
this.data.append("amenityIds", this.amenityIds)
this.data.append("locationId", this.addVenueForm.value.locationId)
this.appService.addBookingItem(this.data).then((resp: any) => {
this.appService.showSimpleAlert("Venue", resp.message, resp.success ? 'success' : 'error');
if (resp.success) {
this.selectedBookingType = []
this.selectedAmenities = []
this.selectedFor = []
this.selectedVenueType = []
this.selectedPictures = []
this.addVenueForm.reset()
this.spinnerService.hide()
}
})
}
这是完美的工作,我正在保存图像路径在mongo
收集。但目前我正在以数组形式发送bookingItem
图像,现在我还想上传thubmnail
图像和cover
图像。那么,我如何分别发送3种类型的图像,并在服务器端获取这3种类型的图像呢?在这里更改表单元素的值:this.data.append('image',item)
,您可以使用类似于image-1-bookingItem
,image-1-thumbnail
,image-1-cover
,然后每增加一个新的,就增加一个。Multer可以帮助您查看哪些文件是基于您上载的文件名的。我在Multer
description上找到了我的答案。我可以通过在multer
中传递字段
数组来实现这一点。谢谢你的帮助