ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

typescript https上传文件

2022-05-19 15:00:25  阅读:34  来源: 互联网

标签:typescript return res formData data https path const 上传


export const requestFormData = async(host:string,path:string,formData:any):Promise<any> =>{
    return new Promise( async (resolve) => {
        const https = require('https');

        const options = {
          hostname: host,
          path: path,
          method: 'POST',
          headers:formData.getHeaders()
        };

        const req = https.request(options, (res) => {
          console.log('statusCode:', res.statusCode);
          console.log('headers:', res.headers);
          let data = "";  
          res.on('data', (d) => {
            return data+=d;
          });
          
          res.on('end', (d) => {
            let jsonData:any = {}
            try{
                jsonData = JSON.parse(data);
            }catch (e){
                return resolve({code:-1,msg:`${e}`})
            }
                return resolve(jsonData)
          });
          
        });

        req.on('error', (e) => {
          console.error(e);
        });
        formData.pipe(req);
        //req.end();
    });
}

export const requestFile = async(host:string,path):Promise<any> =>{
    return new Promise( async (resolve) => {
        const FormData =require('form-data');
        const formData = new FormData();
        const filename="./test.txt"

        // 1.先将字符串转换成Buffer
        const fileContent = Buffer.from("hello");
        // 2.补上文件meta信息
        formData.append(filename, fileContent, {
        filename,
        contentType: 'text/plain',
        knownLength: fileContent.byteLength
        });
        //const fs = require("fs");
        //formData.append("template",fs.createReadStream('./test.txt'))

        let response = await requestFormData(host, path,formData)
        return resolve(response);

    });
}

  

标签:typescript,return,res,formData,data,https,path,const,上传
来源: https://www.cnblogs.com/boye169/p/16288496.html

专注分享技术,共同学习,共同进步。侵权联系[admin#icode9.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有