背景:已知资源的URL,需要在代码中将该文件以FormData的形式传给第三方接口使用
import { HttpService, Injectable } from '@nestjs/common';
var http = require('http');
import { join, basename } from 'path';
const fs = require("fs");
var FormData = require('form-data');
async getHello() {
const vitaUrl = 'http://localhost:8050/123.jpg'
var form = new FormData();
form.append('file', createReadStream(`./public/${basename(vitaUrl )}`));
var headers = form.getHeaders();
var request = http.request({
method: 'post',
host: '47.98.128.88',
port: '8080',
path: '/api/upload/',
headers: headers
},function(res:any){
var str='';
res.on('data',function(buffer:any){
str+=buffer;//用字符串拼接
console.log('拼接',str)
}
);
res.on('end',()=>{
var result = JSON.parse(str);
//上传之后result就是返回的结果
console.log('结果',result)
});
});
form.pipe(request);
}
网友评论