Angular 6文件上传

时间:2018-08-19 17:12:15

标签: node.js angular

我有一个REST API,可将图像上传到s3并返回响应。该API使用Postman可以完美运行。

从前端调用API时出现问题。我正在使用Angular 6。

我遇到Error: Unsupported content type: application/json错误。尽管我正确设置了标题。

这是我的Angular 6代码。

export class UploadComponent {
  percentDone: number;
  uploadSuccess: boolean;

  constructor(private http: HttpClient) {}

  upload(file: File) {
    this.singleBasicUpload(file);
  }

  singleBasicUpload(file: File) {
    const headers = new HttpHeaders({
      'Content-Type': 'multipart/form-data',
    });
    const options = { headers: headers };
    this.http.post(`${BASE_URL}/upload`, file, options).subscribe(response => {
      console.log('response', response);
    });
  }
}

这是我在后端Node.js中的S3代码

AWS.config.update({
  accessKeyId: constants.IAM_USER_KEY,
  secretAccessKey: constants.IAM_USER_SECRET,
});

const BUCKET_NAME = constants.BUCKET_NAME;
const ACL = 'public-read';
const S3 = new AWS.S3();

export async function S3Upload(req, res) {
  const chunks = [];

  let fname;
  let fileType;
  let fileEncodingType;

  const busboy = new Busboy({
    headers: req.headers,
  });

  busboy.on('file', (fieldname, file, filename, encoding, mimetype) => {
    fname = filename.replace(/ /g, '_');
    fileType = mimetype;
    fileEncodingType = encoding;

    file.on('data', data => {
      // you will get chunks here will pull all chunk to an array and later concat it.
      console.log(chunks.length);
      chunks.push(data);
    });
    file.on('end', () => {
      console.log(`File [${filename}] Finished`);
    });
  });
  busboy.on('finish', () => {
    const userId = UUID();
    const params = {
      Bucket: BUCKET_NAME, // your s3 bucket name
      Key: `${userId}-${fname}`,
      Body: Buffer.concat(chunks), // concatinating all chunks
      ACL,
      ContentEncoding: fileEncodingType, // optional
      ContentType: fileType, // required
    };
    // we are sending buffer data to s3.
    S3.upload(params, (err, s3res) => {
      if (err) {
        res.send({
          err,
          status: 'error',
        });
      } else {
        return res.send({
          data: s3res,
          message: 'Image successfully uploaded.',
        });
      }
    });
  });
  req.pipe(busboy);
}

Network description

0 个答案:

没有答案