Skip to content

Instantly share code, notes, and snippets.

@zxhfighter
Created July 21, 2019 01:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zxhfighter/051e460cf1b6ae0afada7c838099ccfe to your computer and use it in GitHub Desktop.
Save zxhfighter/051e460cf1b6ae0afada7c838099ccfe to your computer and use it in GitHub Desktop.
Node 上传文件
const http = require('http');
const {readFileSync} = require('fs');
const {basename, normalize} = require('path');

const token =
    'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIzNjk3NDk0NTZAcXEuY29tIiwiaWF0IjoxNTYzMzcyNDU1LCJleHAiOjE1NjMzNzYwNTV9.3E927Cxom1qWSZ0a8NbVu_4F0NdTL252PCqlv8KiAhA';

function getFileContent(file, boundary) {
    const crlf = '\r\n';
    const delimiter = `${crlf}--${boundary}`;
    const closeDelimiter = `${delimiter}--`;

    const data = readFileSync(file.path);
    return Buffer.concat([
        Buffer.from(
            `${delimiter}${crlf}Content-Disposition: form-data; name="file"; filename="${
                file.name
            }"${crlf}${crlf}`
        ),
        data,
        Buffer.from(
            `${crlf}${delimiter}${crlf}Content-Disposition: form-data; name="name"${crlf}${crlf}${
                file.name
            }`
        ),
        Buffer.from(closeDelimiter)
    ]);
}

function makeRequest(filepath, token) {
    filename = basename(filepath);

    const boundary = `--${Math.random().toString(16)}`;
    const requestBody = getFileContent(
        {
            name: filename,
            path: normalize(filepath)
        },
        boundary
    );

    const req = http.request({
        hostname: 'localhost',
        method: 'POST',
        agent: false,
        path: `/api/project/12/files?name=${filename}`,
        port: 5000,
        headers: {
            Accept: 'application/json',
            Connection: 'keep-alive',
            Authorization: `Bearer: ${token}`,
            'Content-Type': `multipart/form-data; boundary=${boundary}`,
            // 'Content-Length': requestBody.toString('utf8').length,
            // 'Content-Length': Buffer.byteLength(requestBody.toString('utf8')),
            'Content-Length': requestBody.length
        }
    });

    req.on('error', e => {
        console.error(e);
    });
    req.write(requestBody);
    req.end();

    return req;
}

if (require.main === module) {
    makeRequest('./tests/test-upload/2.cf31ca63.chunk.js.map', token);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment