var http = require('http'); var path = require('path'); var fs = require('fs'); function uploadFile(fileKey,absPath){ var req = http.request(genUploadOption(), function(res){ // console.log("RES:" + res); console.log('STATUS: ' + res.statusCode); // console.log('HEADERS: ' + JSON.stringify(res.headers)); res.on("data", function(chunk){ console.log("響應信息:" + chunk); }) }) req.on('error', function(e){ console.log('上傳出現錯誤:' + e.message); console.log(e); }) var boundaryKey = Math.random().toString(16); var endData = '\r\n----' + boundaryKey + '--'; var content = "\r\n----" + boundaryKey + "\r\n" + "Content-Type: application/octet-stream\r\n" + "Content-Disposition: form-data; name=\"" + fileKey + "\"; filename=\"" + path.basename(absPath) + "\"\r\n" + "Content-Transfer-Encoding: binary\r\n\r\n"; var contentBinary = new Buffer(content, 'utf-8'); var contentLength = 0; var stat = fs.statSync(absPath); contentLength += contentBinary.length; contentLength += stat.size; req.setHeader('Content-Type', 'multipart/form-data; boundary=--' + boundaryKey); req.setHeader('Content-Length', contentLength + Buffer.byteLength(endData)); req.write(contentBinary); var fileStream = fs.createReadStream(absPath, {bufferSize : 4 * 1024}); fileStream.pipe(req, {end: false}); fileStream.on('end', function() { req.end(endData); }); } function genUploadOption(){ const ywid = '4499'; // 單據gid、憑證的billid const ywkey = 'fs~XTYWBILLIMAGE~' + ywid; const dataType = 2; // 1:憑證;2:單據;3:單據項目;4:管理對象;5:其它 const typeId = "54020"; const userCode = "388610"; const dwdh = "0001"; return { hostname: 'ygfs.ygsoft.com', port: 9080, path: "/grm/gris/contentmanage.collectStageServlet" + "?beanId=com.ygsoft.ecp.component.contentmanage.service.context.ICollectStageContext" + "&method=saveUploadFile" + "&needSave=true" + "&isScan=true" + "&nativeType=true" + "&needReturnValue=true" + "&ywKey=" + ywkey + "&ywid=" + ywid + "&dataType=" + dataType + "&billType=" + typeId + "&userCode=" + userCode + "&systemCode=GRIS" + "&systemId=00" + "&bizBillTypeId=11111111111111111111111111111111" + "&dwdh=" + dwdh + "&dateCode=00" + "&folderId=462844", method: 'POST' }; } uploadFile("file1",'C:\\Users\\liwenjun\\Desktop\\OffLine.jpg');