[英]VueJS - How to send a POST request of a JSON array each including data in addition to a File or Picture for each array element
[英]How to make a POST request for each file in array
我在angular組件中有一個拖放文件數組。 我想對它們每個發出POST請求到http://some.url
。 我正在嘗試執行以下操作:
drop.component.ts
public drop(event) {
* somehow set droppedFiles *
let observables = [];
this.droppedFiles.forEach(file => observables.push(this.uploadFile(file)));
forkJoin(observables);
}
public uploadFile(image) {
return this.imagesService.saveImage(image, this.tigerId).pipe(first()).subscribe(
(data: ISaveImageResponse) => {
console.log(data);
return;
},
error => {
console.error(error);
return;
}
);
}
images.service.ts
public saveImage(image: File): Observable<ISaveImageResponse> {
let imageInfo = {
name: null, type: null, image: null
};
imageInfo.name = [image.name, Validators.required];
imageInfo.type = [image.type, Validators.required];
imageInfo.image = null;
let form = this.formBuilder.group(imageInfo);
form.get('image').setValue(image);
const formModel = this.prepareFormData(form);
return this.http.post<any>(
'http://some.url',
formModel
).pipe(
map((imageInfo: any) => {
return imageInfo
}),
catchError((error, caught) => {
return EMPTY;
})
);
}
如果我刪除單個文件,則工作正常。 但是,如果有多個文件,請求將變為掛起狀態,但我看不到它們已記錄到服務器(即express.js服務器)中。
問題是什么?
更新
我已經將代碼更新為實際的代碼:現在uploadImage()
返回Observable
並從forkJoin()
調用請求
更新2
經過一段時間的請求待處理后,服務器控制台中出現以下錯誤:
(node:1291) MaxListenersExceededWarning: Possible EventEmitter memory leak detected.
11 field listeners added. Use emitter.setMaxListeners() to increase limit
但是根本沒有關於請求的信息發生(對於我所做的任何請求,例如console.log('POST /images');
)
更新3
用於處理POST請求的服務器端代碼:
server.js
const server = express();
const fs = require("fs");
const path = require('path');
const passport = require('passport');
const session = require('express-session');
const RedisStore = require('connect-redis')(session);
server.use(
session({
store: new RedisStore({
url: config.redisStore.url
}),
secret: config.redisStore.secret,
resave: false,
saveUninitialized: false
})
);
server.use( passport.initialize() );
server.use( passport.session() );
server.use( cors({ origin: '*' }) );
server.use( bp.json() );
server.use( express.static('uploads') );
server.use( require('./image.routes') );
const port = 9901;
server.listen(port, () => {
const dir = __dirname + '/uploads';
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir);
}
console.log('We are live on ' + port);
});
image.routes.js
const fs = require('fs');
const formidable = require('express-formidable');
const path = require('path');
let router = express.Router();
router.post('/images',
formidable({
encoding: 'utf-8',
uploadDir: path.resolve(__dirname, 'uploads'),
multiples: true,
keepExtensions: true
}),
(req, res, next) => {
console.log('\nPOST /images');
const image = req.fields;
const data = req.files;
image.path = data.image.path;
const file = fs.createReadStream(image.path);
createImage(image).then( // createImage() saves image info to db
result => {
if (result) {
res.status(200).send(result);
} else {
console.error("Cannot save image");
res.status(400).send("Cannot save image");
}
}).catch(e => console.error(e.stack));
});
module.exports = router;
您不能使用Promise.all
處理Rxjs請求。
您可以使用forkJoin一次發出多個Observale請求,
public drop(event) {
* somehow set droppedFiles *
let observables = []
this.droppedFiles.forEach(file => observables.push(this.uploadFile(file)));
Rx.Observable.forkJoin(observables)
}
而且您的uploadFile
函數沒有返回可觀察到的
public uploadFile(image) {
return this.imagesService.saveImage(image, this.tigerId).pipe(first())
}
在此處查看示例5
嘗試使用“ map”或“ for”代替forEach。
public drop(event) {
* somehow set droppedFiles *
Promise.all(this.droppedFiles.map(file => this.uploadFile(file)));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.