Файл не сохраняется в правильном формате с помощью ngx-file-drop в приложении angular 7 - PullRequest
0 голосов
/ 09 июля 2019

Я реализовал функцию загрузки файлов с помощью ngx-file-drop в приложении angular 7. В настоящее время я был в состоянии сохранить файлы в базе данных, но думаю, что он не сохраняет его в правильном формате. Я конвертирую файл в bytearray на стороне сервера перед сохранением. Я не уверен, что проблема на стороне сервера или в том, как я отправляю файл с клиента. Файл загружается неправильно и выдает ошибку, говоря не в нужном формате. Когда я загружаю тот же файл через другой инструмент, он читается правильно. Согласно их документации https://www.npmjs.com/package/ngx-file-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();
            }
        }
...