我已经在angular 7应用程序中使用ngx-file-drop实现了文件功能的上传。我目前已经能够将文件保存到数据库中,但是我猜它没有以正确的格式保存它。我先将文件转换为服务器端的字节数组,然后再保存。我不确定问题出在服务器端还是我从客户端发送文件的方式。文件未正确加载,并且错误地指出格式不正确。当我通过其他工具上载相同文件时,其正确读取。 根据文档https://www.npmjs.com/package/ngx-file-drop,文件被封装为formdata的一部分,并被发布到drop事件中。就我而言,它不仅需要保存文件,还需要保存其他数据。因此,我创建了一个接口,该接口封装了文件以及称为IDocumentUpload的其他数据
UI
<div class="center" class="file-upload-wrapper">
<ngx-file-drop dropZoneLabel="Drop files here" dropZoneClassName="file-drop" multiple="true"
(onFileDrop)="dropped($event)" (onFileOver)="fileOver($event)" (onFileLeave)="fileLeave($event)">
<ng-template ngx-file-drop-content-tmp let-openFileSelector="openFileSelector">
<button type="button" (click)="openFileSelector()">Drop Files to Upload</button>
</ng-template>
</ngx-file-drop>
<div class="upload-table">
<table id="table1" class="center">
<tbody class="upload-name-style">
<tr *ngFor="let item of files; let i=index">
<td> <input kendoTextBox [(ngModel)]="item.name" style="width: 350px" /></td>
<td>
<kendo-dropdownlist style="width:350px" [(ngModel)]="item.selectedDocumentItem"
[data]="DocumentTypes" [filterable]="false" textField="Name" valueField="Id">
</kendo-dropdownlist>
</td>
<td>
<kendo-datepicker style="width: 200px" [format]="'dd MMM, yyyy'" [value]="item.selectedDate"
[(ngModel)]="item.selectedDate"></kendo-datepicker>
</td>
<td> <button class="btn btn-default" (click)="deleteRow(i)"><i
class="fa fa-trash"></i>Delete
</button></td>
</tr>
</tbody>
</table>
</div>
<div class="wrapper">
<button *ngIf="files.length > 0" type="button" (click)="createDocument()" [disabled]="upload"
class="btn btn-primary btn-upload">upload</button>
</div>
</div>
组件
export interface IDocumentUpload {
fileDropEntry: NgxFileDropEntry;
name: string;
selectedDocumentItem: { 'Id': number; 'Name': string; }
selectedDate: Date;
}
public files: IDocumentUpload[] = [];
public dropped(files: NgxFileDropEntry[]) {
for (const droppedFile of files) {
if (droppedFile.fileEntry.isFile) {
const fileEntry = droppedFile.fileEntry as FileSystemFileEntry;
fileEntry.file((file: File) => {
// const formData = new FormData();
// formData.append('logo', file);
});
}
}
this.files = files.map(file => ({
name: file.relativePath,
selectedDocumentItem: { Name: 'Select Category', Id: null },
selectedDate: new Date(),
fileDropEntry: file
}));
this.upload = false;
}
public createDocument() {
const documents: IDocumentDetails[] = this.files.map(doc => {
return { // notice just a curly bracket, and in the same line with 'return'
file: doc.fileDropEntry.fileEntry,
documentTypeId: doc.selectedDocumentItem.Id,
name: doc.name,
documentDate: doc.selectedDate
};
});
this.documents = { managerStrategyId: 0, documentDetails: null };
this.documents.managerStrategyId = this.ManagerStrategyId;
this.documents.documentDetails = documents;
this.documentUploadService.createDocumentUpload(this.documents)
.then((result) => {
if (result) {
this.documentIds.ids = Object.keys(result).map(k => result[k]);
this.getDocumentUploadDetailsByIds(this.documentIds.ids.toString());
this.setGridOptions();
this.setColumns();
this.notify.success('Documents uploaded Successfully');
this.upload = true;
}
}).catch(err => {
this.notify.error('An Error Has Occured While uploading the documents');
});
}
服务器代码-asp.net webapi
[HttpPost]
[SkipTokenAuthorization]
[Route("api/documentupload/create")]
public List<int> Create(DocumentUploadCreateViewModel model)
{
HttpResponseMessage response;
var mgrStrategyDocument = new MANAGERSTRATEGY_DOCUMENT();
var mgrDocumentService = GetService<DOCUMENT>();
var mgrStrategyDocumentService = GetService<MANAGERSTRATEGY_DOCUMENT>();
List<int> documentIds = new List<int>();
if (model != null)
{
foreach (var obj in model.DocumentDetails)
{
var mgrDocument = new DOCUMENT
{
DOCUMENT_TYPE_ID = obj.DocumentTypeId,
DOCUMENT_DATE = obj.DocumentDate,
NAME = obj.Name,
DOCUMENT_CONTENT = File.ReadAllBytes(obj.file),
EXTENSION = GetFileExtension(obj.Name)
};
mgrDocument = mgrDocumentService.Create(mgrDocument);
documentIds.Add(mgrDocument.ID);
var mangerStrategyDocumentService = GetService<MANAGERSTRATEGY_DOCUMENT>();
var mgrStrategyDocument1 = new MANAGERSTRATEGY_DOCUMENT()
{
DOCUMENT_ID = mgrDocument.ID,
MANAGERSTRATEGY_ID = model.ManagerStrategyId
};
mgrStrategyDocument = mgrStrategyDocumentService.Create(mgrStrategyDocument1);
}
return documentIds;
}
return null;
}
private byte[] convertByteArray(object file)
{
BinaryFormatter bf = new BinaryFormatter();
using (var ms = new MemoryStream())
{
file = Newtonsoft.Json.JsonConvert.SerializeObject(file);
bf.Serialize(ms, file);
return ms.ToArray();
}
}