Файлы, загруженные в корзину s3, повреждены, используя aws-sdk, multer и multer-s3 для загрузки файлов непосредственно в s3. - PullRequest
0 голосов
/ 01 ноября 2019

add-schedule.component.html -

<div class="container">
  <form [formGroup]="form" (ngSubmit)="onSubmit()">
  <div class="row">
    <div class="col-md-12">
      <h3 class="header">Notes</h3>
      <hr>
    </div>
    <div class="col-md-12">
      <mat-form-field style="width: 100%">
        <mat-select formControlName="semBatch" placeholder="Select Semester & Batch">
          <mat-option *ngFor="let opt of options" [value]="opt">{{ opt }}</mat-option>
        </mat-select>
      </mat-form-field>
    </div>
    <div class="col-md-12">
        <button type="submit" [disabled]="form.invalid" mat-raised-button class="updateBtn">Update</button>
        <input formControlName="timetableFile" type="file" style="display:none"  #sem>
        <button class="color fileUp" mat-raised-button type="button" (click)="sem.click()">Pick
          File</button>
        <small class="grey" *ngIf="form.get('timetableFile').value">
          {{ (form.get('timetableFile').value).substring(12) }} </small>
    </div>
  </div>
</form>
</div>

add-schedule.component.ts -

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { TimetableService } from '../services/timetable.service';

@Component({
  selector: 'app-add-timetable',
  templateUrl: './add-timetable.component.html',
  styleUrls: ['./add-timetable.component.css']
})
export class AddTimetableComponent implements OnInit {

  form: FormGroup;
  options = ['Semester 1 Batch A', 'Semester 1 Batch B', 'Semester 2 Batch A', 'Semester 2 Batch B',
  'Semester 3 Batch A', 'Semester 3 Batch B', 'Semester 4 Batch A', 'Semester 4 Batch B', 'Semester 5 Batch A', 'Semester 5 Batch B'];

  constructor(public timetableService: TimetableService) { }

  ngOnInit() {
    this.form = new FormGroup({
      semBatch: new FormControl(null, Validators.required),
      timetableFile: new FormControl(null, Validators.required)
    });
  }

  onSubmit() {
    this.timetableService.addTimetable(this.form.value.semBatch, this.form.value.timetableFile);
  }

}

schedule.service.ts -

addTimetable(semBatch: string, timetableFile: string) {

    const postData = new FormData();

    postData.append('semBatch', semBatch);
    postData.append('timetableFile', timetableFile);

    this.http.post<any>( environment.api_url + 'addTimetable', postData).subscribe(result => {
      this.semBatch.next(result.doc);
      this.router.navigate(['/timeTable']);
    });
  }

aws config в файле app.js -

const s3 = new aws.S3({
  secretAccessKey: process.env.SECRET_ACCESS_KEY,
  accessKeyId: process.env.ACCESS_KEY_ID,
  region: process.env.REGION
});

const uploadParams = {
  Bucket: process.env.BUCKET,
  Key: '', // pass key
  Body: null, // pass file body
};

const upload = multer({
  storage: multerS3({
    s3: s3,
    bucket: process.env.BUCKET,
    metadata: function (req, file, cb) {
      cb(null, {fieldName: file.fieldname});
    },
    key: function (req, file, cb) {
      cb(null, Date.now().toString());
    }
  })
});

api url в приложении.js -

app.post('/addTimetable', upload.single('timetableFile'), checkAuth, (req, res)=> {

        let fileName = Date.now() + ' ' + (req.body.timetableFile).substring(12);

        let ext = (req.body.timetableFile).substring(12).split('.').pop();

        if (ext === 'pdf') {

        let type = 'application/pdf';

        let params = uploadParams;

        uploadParams.Key = fileName;
        uploadParams.Body = req.body.timetableFile;
        uploadParams.ContentType = type;

        s3.upload(params, (err, data) => {

        if (err)
        {
          res.status(400).json({
            message: "Failed to Upload Timetable File for the Following Reason : " + err
          });
        }

        function addTimetable() {

            Timetable.findOne({ semBatch: req.body.semBatch }, (error, doc) => {

              if(error) {
                res.status(500).json({
                  message: "Failed to Fetch Timetable for the Following Reason : " + error
                });
              }
              else if(doc) {

                Timetable.findOneAndUpdate({ semBatch: req.body.semBatch}, { $set: { fileUrl:  data.Location }})
                .then(() => {
                  Timetable.find({}, (error, doc) => {
                    if(!error) {
                      res.status(200).json({
                        doc: doc
                      });
                    }
                  });
                })
                .catch(error => {
                  res.status(500).json({
                    message: "Failed to Update Timetable for the Following Reason : " + error
                  });
                });
              } else {

                const tt = new Timetable({
                  semBatch: req.body.semBatch,
                  fileUrl: data.Location
                });

                tt.save()
                .then(() => {
                  Timetable.find({}, (error, doc) => {
                    if(!error) {
                      res.status(200).json({
                        doc: doc
                      });
                    }
                  });
                }).catch(error => {
                  res.status(500).json({
                    message: "Failed to Save Timetable for the Following Reason : " + error
                  });
                });
              }
            }).catch(error => {
              res.status(500).json({
                message: "Failed to Add Timetable for the Following Reason : " + error
            });
          });
        }
        setTimeout(addTimetable, 1000);
  });
        } else {
          res.status(400).json({
            message: "Invalid File Type Please Upload File with .pdf"
          });
        }
});

я дал публичный доступ к своему ведру с помощью политики, а также снял флажок блокировать весь доступ.

файлы успешно загружаются, но когда я загружаю их на стороне клиентачерез его URL они повреждены, даже когда я загружаю напрямую через корзину

...