收藏
回答

关于uploadFile HTTPAPI的使用问题

在使用uploadFile HTTPAPI在桌面端上传文件到云存储出现以下问题:(这里是使用nodejs开发桌面端程序,使用的是electron框架)

在程序运行后第一次上传是正常的(单张多张都是正常运行),但是第二次正常调用程序报错,无法判断是什么原因造成的,求解答

/**
 * 将文件图片传到云端(单张图片)
 * @param {*} readImageRes_now 获取的新增的图片信息
 * @param {*} directoryPath 目标图片的地址
 * @returns 
 */
const uploadfile = async (readImageRes_now, directoryPath) => {
    //获取AccessToken
    let access_token = await getAccessToken();
    let uplodaPath = 'ARPhotoImage/' + readImageRes_now;
    let uplodUrl = `https://api.weixin.qq.com/tcb/uploadfile?access_token=${access_token}`;
    let getUpdalodRes = await axios({
        method: 'post',
        url: uplodUrl,
        data: {
            'env': envData.ENVID,
            'path': uplodaPath,
        }
    });
    let data = getUpdalodRes.data;
    //读取url的二进制文件
    //图片文件路径
    let imageUrl = path.join(directoryPath, readImageRes_now);
    let file = fs.createReadStream(imageUrl);//二进制文件
    try {
        axios.defaults.headers.post["Content-Type"] = 'multipart/form-data';
        await axios({
            method: 'post',
            url: data.url,
            data: {
                'key': uplodaPath,
                "Signature": data.authorization,
                'x-cos-security-token': data.token,
                "x-cos-meta-fileid": data.cos_file_id,
                'file': file,
            }
        });
        console.log(data.file_id);
        return data.file_id;
    } catch (error) {
        console.log(error);
    }

}

//上传多张图片
const uploadfiles = (currentArray, directoryPath) => {
    let promiseArray = [];
    for (let i = 0; i < currentArray.length; i++) {
        promiseArray.push(uploadfile(currentArray[i], directoryPath));
    }
    Promise.all(promiseArray).then((res) => {
        console.log("数据上传结束:", res);
    }).catch((err) => {
        console.log(err);
    });
}

//报错信息
AxiosError [AggregateError]
    at AxiosError.from (C:\Users\1MU\Desktop\ARPhoto_backend\node_modules\axios\dist\node\axios.cjs:836:14)
    at RedirectableRequest.handleRequestError (C:\Users\1MU\Desktop\ARPhoto_backend\node_modules\axios\dist\node\axios.cjs:3086:25)
    at RedirectableRequest.emit (node:events:514:28)
    at eventHandlers.<computed> (C:\Users\1MU\Desktop\ARPhoto_backend\node_modules\follow-redirects\index.js:38:24)
    at ClientRequest.emit (node:events:514:28)
    at Socket.socketErrorListener (node:_http_client:495:9)
    at Socket.emit (node:events:514:28)
    at emitErrorNT (node:internal/streams/destroy:151:8)
    at emitErrorCloseNT (node:internal/streams/destroy:116:3)
    at process.processTicksAndRejections (node:internal/process/task_queues:82:21)
    at Axios.request (C:\Users\1MU\Desktop\ARPhoto_backend\node_modules\axios\dist\node\axios.cjs:3876:41)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async uploadfile (C:\Users\1MU\Desktop\ARPhoto_backend\utils\uploadFiles.js:41:9)
    at async Promise.all (index 0) {
  code: 'ECONNREFUSED',
  errors: [
    Error: connect ECONNREFUSED 127.0.0.1:80
        at createConnectionError (node:net:1634:14)
        at afterConnectMultiple (node:net:1664:40) {
      errno: -4078,
      code: 'ECONNREFUSED',
      syscall: 'connect',
      address: '127.0.0.1',
      port: 80
    },
    Error: connect ECONNREFUSED ::1:80
        at createConnectionError (node:net:1634:14)
        at afterConnectMultiple (node:net:1664:40) {
      errno: -4078,
      code: 'ECONNREFUSED',
      syscall: 'connect',
      address: '::1',
      port: 80
    }
  ],
  config: {
    transitional: {
      silentJSONParsing: true,
      forcedJSONParsing: true,
      clarifyTimeoutError: false
    },
    adapter: [ 'xhr', 'http' ],
    transformRequest: [ [Function: transformRequest] ],
    transformResponse: [ [Function: transformResponse] ],
    timeout: 0,
    xsrfCookieName: 'XSRF-TOKEN',
    xsrfHeaderName: 'X-XSRF-TOKEN',
    maxContentLength: -1,
    maxBodyLength: -1,
    env: { FormData: [Function], Blob: [class Blob] },
    validateStatus: [Function: validateStatus],
    headers: Object [AxiosHeaders] {
      Accept: 'application/json, text/plain, */*',
      'Content-Type': 'multipart/form-data; boundary=--------------------------699436463274739593603861',
      'User-Agent': 'axios/1.6.8',
      'Content-Length': '115848',
      'Accept-Encoding': 'gzip, compress, deflate, br'
    },
    method: 'post',
    data: FormData {
      _overheadLength: 279,
      _valueLength: 48,
      _valuesToMeasure: [Array],
      writable: false,
      readable: true,
      dataSize: 0,
      maxDataSize: 2097152,
      pauseStreams: true,
      _released: true,
      _streams: [],
      _currentStream: null,
      _insideLoop: false,
      _pendingNext: false,
      _boundary: '--------------------------699436463274739593603861',
      _events: [Object: null prototype],
      _eventsCount: 3
    }
  },
  request: <ref *1> Writable {
    _writableState: WritableState {
      state: 802924,
      highWaterMark: 16384,
      defaultEncoding: 'utf8',
      length: 0,
      corked: 0,
      onwrite: [Function: bound onwrite],
      writecb: null,
      writelen: 0,
      afterWriteTickInfo: null,
      buffered: [],
      bufferedIndex: 0,
      pendingcb: 0,
      errored: null,
      [Symbol(kOnFinished)]: []
    },
    _events: [Object: null prototype] {
      response: [Function: handleResponse],
      error: [Function: handleRequestError],
      socket: [Function: handleRequestSocket]
    },
    _eventsCount: 3,
    _maxListeners: undefined,
    _options: {
      maxRedirects: 21,
      maxBodyLength: Infinity,
      protocol: 'http:',
      path: '/undefined',
      method: 'POST',
      headers: [Object: null prototype],
      agents: [Object],
      auth: undefined,
      family: undefined,
      beforeRedirect: [Function: dispatchBeforeRedirect],
      beforeRedirects: [Object],
      hostname: 'localhost',
      port: '',
      agent: undefined,
      nativeProtocols: [Object],
      pathname: '/undefined'
    },
    _ended: true,
    _ending: true,
    _redirectCount: 0,
    _redirects: [],
    _requestBodyLength: 115848,
    _requestBodyBuffers: [
      [Object], [Object],
      [Object], [Object],
      [Object], [Object],
      [Object]
    ],
    _onNativeResponse: [Function (anonymous)],
    _currentRequest: ClientRequest {
      _events: [Object: null prototype],
      _eventsCount: 7,
      _maxListeners: undefined,
      outputData: [],
      outputSize: 0,
      writable: true,
      destroyed: false,
      _last: false,
      chunkedEncoding: false,
      shouldKeepAlive: true,
      maxRequestsOnConnectionReached: false,
      _defaultKeepAlive: true,
      useChunkedEncodingByDefault: true,
      sendDate: false,
      _removedConnection: false,
      _removedContLen: false,
      _removedTE: false,
      strictContentLength: false,
      _contentLength: '115848',
      _hasBody: true,
      _trailer: '',
      finished: true,
      _headerSent: true,
      _closed: false,
      socket: [Socket],
      _header: 'POST /undefined HTTP/1.1\r\n' +
        'Accept: application/json, text/plain, */*\r\n' +
        'Content-Type: multipart/form-data; boundary=--------------------------699436463274739593603861\r\n' +
        'User-Agent: axios/1.6.8\r\n' +
        'Content-Length: 115848\r\n' +
        'Accept-Encoding: gzip, compress, deflate, br\r\n' +
        'Host: localhost\r\n' +
        'Connection: keep-alive\r\n' +
        '\r\n',
      _keepAliveTimeout: 0,
      _onPendingData: [Function: nop],
      agent: [Agent],
      socketPath: undefined,
      method: 'POST',
      maxHeaderSize: undefined,
      insecureHTTPParser: undefined,
      joinDuplicateHeaders: undefined,
      path: '/undefined',
      _ended: false,
      res: null,
      aborted: false,
      timeoutCb: [Function: emitRequestTimeout],
      upgradeOrConnect: false,
      parser: null,
      maxHeadersCount: null,
      reusedSocket: false,
      host: 'localhost',
      protocol: 'http:',
      _redirectable: [Circular *1],
      [Symbol(kCapture)]: false,
      [Symbol(kBytesWritten)]: 0,
      [Symbol(kNeedDrain)]: true,
      [Symbol(corked)]: 0,
      [Symbol(kOutHeaders)]: [Object: null prototype],
      [Symbol(errored)]: null,
      [Symbol(kHighWaterMark)]: 16384,
      [Symbol(kRejectNonStandardBodyWrites)]: false,
      [Symbol(kUniqueHeaders)]: null
    },
    _currentUrl: 'http://localhost/undefined',
    [Symbol(kCapture)]: false
  },
  cause: AggregateError
      at internalConnectMultiple (node:net:1114:18)
      at afterConnectMultiple (node:net:1667:5) {
    code: 'ECONNREFUSED',
    [errors]: [ [Error], [Error] ]
  }
}
回答关注问题邀请回答
收藏

2 个回答

  • 灼小妖
    灼小妖
    04-11

    已解决

    /**
     * 将文件图片传到云端(单张图片)
     * @param {*} readImageRes_now 获取的新增的图片信息
     * @param {*} directoryPath 目标图片的地址
     * @returns 
     */
    const uploadfile = async (readImageRes_now, directoryPath) => {
        //获取AccessToken
        let access_token = await getAccessToken();
        let uplodaPath = 'ARPhotoImage/' + readImageRes_now;
        let uplodUrl = `https://api.weixin.qq.com/tcb/uploadfile?access_token=${access_token}`;
        console.log(typeof envData.ENVID, typeof uplodaPath);
        let getUpdalodRes = await axios({
            method: 'post',
            url: uplodUrl,
            data: {
                'env': envData.ENVID,
                'path': uplodaPath,
            }
        });
        let data = getUpdalodRes.data;
        //读取url的二进制文件
        //图片文件路径
        let imageUrl = path.join(directoryPath, readImageRes_now);
        let file = fs.createReadStream(imageUrl);//二进制文件
        console.log("获取上传链接:", data);
        // axios.defaults.headers.post["Content-Type"] = 'multipart/form-data';
        await axios({
            method: 'post',
            url: data.url,
            headers: {
                "Content-Type": 'multipart/form-data',
            },
            data: {
                'key': uplodaPath,
                "Signature": data.authorization,
                'x-cos-security-token': data.token,
                "x-cos-meta-fileid": data.cos_file_id,
                'file': file,
            }
        });
        // console.log(data.file_id);
        return data.file_id;
    
    }
    
    
    const uploadfiles = (currentArray, directoryPath) => {
        let promiseArray = [];
        for (let i = 0; i < currentArray.length; i++) {
            promiseArray.push(uploadfile(currentArray[i], directoryPath));
        }
        Promise.all(promiseArray).then((res) => {
            // console.log("数据上传结束:", res);
        }).catch((err) => {
            console.log(err);
        });
    }
    
    04-11
    有用
    回复
  • Mr.Zhao
    Mr.Zhao
    04-11

    这个问题跟api有关系?

    04-11
    有用
    回复 4
    • 灼小妖
      灼小妖
      04-11
      目前判断应该是没有的
      04-11
      回复
    • Mr.Zhao
      Mr.Zhao
      发表于小程序端
      04-11回复灼小妖

      第二次调用是啥意思

      04-11
      回复
    • Mr.Zhao
      Mr.Zhao
      发表于小程序端
      04-11回复灼小妖

      每一步代码都写下console.log输出下

      04-11
      回复
    • 灼小妖
      灼小妖
      04-11回复Mr.Zhao
      目前业务是这样的,桌面端程序监听文件夹文件变化,把目标图片上传到云存储,运行桌面端程序,在文件第一次发生变化的时候图片是能够上传的,多张图片都是可以的,但是当文件第二次发生变化时就会报上面那个错,之后上传都是会报错,上传地址能拿到,就是最后上传会报错
      04-11
      回复
登录 后发表内容