ОШИБКА TypeError: Невозможно прочитать свойство '0' из неопределенного, используя средний стек - PullRequest
0 голосов
/ 21 марта 2019

В моем TS-файле я написал this.accountService.sendFile (event.target.files [0]) ..... Это выдает ошибку вроде

ОШИБКА TypeError: Невозможно прочитать свойство '0'неопределенного в FileReader.reader.onload (editor.component.ts: 448) в ZoneDelegate.push ../ node_modules / zone.js / dist / zone.js.ZoneDelegate.invoke (zone.js: 392) в Object.onInvoke(core.js: 4630) в ZoneDelegate.push ../ node_modules / zone.js / dist / zone.js.ZoneDelegate.invoke (zone.js: 391) в Zone.push ../ node_modules / zone.js / dist/zone.js.Zone.runGuarded (zone.js: 155) в FileReader.(zone.js: 133)

, а также изображение не сохраняется в бэкэнд-папку.Но путь сохраняется в базу данных.Я новичок в Meanstack.Может кто-нибудь, пожалуйста, помогите.

Заранее спасибо.

Мой HTML

<div *ngFor="let ill of illustrations; let j = index">
      <div *ngIf="j === k">
        <div class="illustration" *ngFor="let illus of ill; let i = index">
          <span style="font-size:20px; font-weight: bold">{{i+1}}. </span>
          <input type="file" style="display:none" #w accept="image/*" (change)="preview($event, j, i)">
          <mat-form-field>
            <input type="text" [(ngModel)]="illustrations[j][i].title" matInput placeholder="Add an Illustration of your article with title & image"
              style="font-size: 20px;font-weight: bold;" required>
            <button matTooltip="Select Illustration Image" matSuffix style="min-width:50px" (click)="w.click()"
              mat-button color="accent">
              <i class="material-icons">insert_photo</i>
            </button>
          </mat-form-field>
        </div>
      </div>
    </div>

My Ts File

preview(event, j, i) {
        if (event.target.files && event.target.files[0]) {

            // console.log(event.target.files);
            // console.log(event.target.files[0]);
            var reader = new FileReader();
               reader.onload = (event: any) => {
                this.illustrations[j][i].imagePath = event.target.result;
                //Upload Image here and apply the path to the this.illustrations[j][i].imagePath

                this.accountService.sendFile(**event.target.files[0]**, localStorage.getItem('userId'), localStorage.getItem('articleId'), 'Illustrations').subscribe(
                    response => {
                        alert(response);
                        this.illustrations[j][i].imagePath = JSON.parse(response).path;
                    },
                    err => {
                        alert(err.message);
                    });
            }
            reader.readAsDataURL(event.target.files[0]);
            // alert(this.illustrations[j][i].title);

        }
    }

Мой сервис

sendFile(fileToUpload: File, userId, articleId, fileSection) {
    const formData: FormData = new FormData();
    formData.append('file', fileToUpload);
    return this.http.post(this.apiPath + 'user/article/saveFiles/' + userId + '/' + articleId + '/' + fileSection, formData, { responseType: 'text' });

  }

Мой контроллер

router.post('/saveArticleAuthors', function (req, res) {
    // console.log(req.body);
    Collections.user.updateOne({ _id: req.body._id },
        { $push: { "stack": { dataName: "selectedAuthors", dataValue: req.body.authors } } },

        function (error, resp) {
            if (error) return console.log("Error: " + error.message);
            res.status(200).send(resp);
        });
});

router.post('/saveFiles/:userId/:articleId/:fileSection', function (req, res) {
    var userId = req.params.userId;
    var fileSection = req.params.fileSection;
    var articleId = req.params.articleId;
    var dirName = SERVER_DIR + userId + '/articles/' + articleId + '/' + fileSection;

    var filename = '';
    //Defining a result JSON for sending status as response
    var result = {
        dbStatus: {},
        fileStatus: false,
        path: false
    };
    //Middleware for Uploading Files
    var storage = multer.diskStorage({
        destination: function (req, file, cb) {
            cb(null, dirName);
        },
        filename: function (req, file, cb) {
            filename = Date.now() + path.extname(file.originalname);
            console.log(file);
            cb(null, filename);
        }
    });
    var upload = multer({ storage: storage }).array('file');
    upload(req, res, function (err) {
        if (err) {
            return res.end(err.toString());
        }
        result.fileStatus = "uploaded";
        result.path = dirName + '/' + filename;
        res.send(result);
        console.log(result);
    });
});
...