我们在我们的应用程序中集成了 OnlyOffice 编辑器。我想将一个 .docx 文件从我的 PC 上传到 OnlyOffice 服务器,以便我们以后可以使用它进行编辑。我正在使用 formdata 向服务器发出 POST 请求,但它不起作用。以下是我的 javascript 代码:
app.post('/topic/:id/upload', (req, res) => {
docManager.init(__dirname, req, res);
//docManager.storagePath(''); // mkdir if not exist
const userIp = docManager.curUserHostAddress();
const uploadDir = `./public/${configServer.get('storageFolder')}/${userIp}`;
const form = new formidable.IncomingForm();
form.uploadDir = uploadDir;
form.keepExtensions = true;
form.parse(req, (err, fields, files) => {
const file = files.uploadedFile;
file.name = docManager.getCorrectName(file.name);
if (configServer.get('maxFileSize') < file.size || file.size <= 0) {
fs.unlinkSync(file.path);
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.write('{ "error": "File size is incorrect"}');
res.end();
return;
}
const exts = [].concat(
configServer.get('viewedDocs'),
configServer.get('editedDocs'),
configServer.get('convertedDocs')
);
const curExt = fileUtility.getFileExtension(file.name);
if (exts.indexOf(curExt) === -1) {
fs.unlinkSync(file.path);
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.write('{ "error": "File type is not supported"}');
res.end();
return;
}
fs.rename(file.path, `${uploadDir}/${file.name}`, (err2) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
if (err2) {
res.write(`{ "error": "${err2}"}`);
} else {
res.write(`{ "filename": "${file.name}"}`);
const userid = req.query.userid ? req.query.userid : 'uid-1';
const firstname = req.query.firstname ? req.query.firstname : 'Jonn';
const lastname = req.query.lastname ? req.query.lastname : 'Smith';
docManager.saveFileData(file.name, userid, `${firstname} ${lastname}`);
docManager.getFileData(file.name, docManager.curUserHostAddress());
}
res.end();
});
});
});
一开始,在 form.parse() 调用中,有一个 files 数组。这个数组是空的。因此,我收到以下错误:
TypeError:无法读取未定义的属性“名称”
以下是我的组件代码:
uploadFile(topicId: any, files: File[]) {
this.fileToUpload = files[0];
let apiUrl = "/topic/" + topicId + "/upload";
let headers = new Headers();
headers.append('authorization', 'Bearer ' + localStorage.getItem('id_token'));
headers.append('Access-Control-Allow-Origin', '*');
let data = new FormData();
data.append('file', this.fileToUpload);
this.ooApiService.postUrl(apiUrl, data, {headers})
.toPromise()
.catch(
(error: any) => this.handleError(error)
);
}
HTML 代码:
<form action="/upload" enctype="multipart/form-data" method="post">
<input class="chooseFile" id="uploadedFile" type="file" [disabled]="isChosen" #fileInput (change)="chooseImage(fileInput.files)"/>
<button *ngIf="userCanEditDetails" md-raised-button color="primary" (click)="uploadFile(topic.id, fileInput.files)">
{{ "Upload file" | translate }}
</button>
</form>
我正在从 angular2 中的客户端应用程序调用此 POST 请求,从那里我选择文件并将其作为表单数据传递。有人可以帮我解决这个问题吗?提前致谢。