node【UTF-8】解碼出錯,懸而未決
阿新 • • 發佈:2019-01-04
上傳壓縮包檔名為【A你你】,node後端獲取到檔名變成了【A浣犱綘】。歡迎大神留言指導。
前端檔案上傳的post請求資訊如下:
伺服器端程式碼如下:
採用iconv嘗試了多種編碼和解碼方法,還是沒能正確還原字串。對照了utf-8漢字編碼是正確的,解碼結果不正確。
var buf = new Buffer( file.name.split('.')[0], 'UTF-8'); // console.log(buf.toString('UTF-8')); console.log(buf); buf = iconv.decode(buf,'UTF-8'); console.log(buf); // var temp = iconv.decode(buf,'utf-8'); console.log("gbkBytes======================="); var gbkBytes = iconv.encode(file.name.split('.')[0],'gbk'); console.log(gbkBytes); gbkBytes = iconv.decode(gbkBytes,'gbk'); console.log(gbkBytes); console.log("binary======================="); var binary = iconv.encode(file.name.split('.')[0],'binary'); console.log(binary); binary = iconv.decode(binary,'UTF-8'); console.log(binary); console.log("end=======================");
後臺輸出如下
utf-8編碼=======================
<Buffer 41 e4 bd a0 e4 bd a0>
QeS9oOS9oA==
gbk編碼=======================
<Buffer 41 c4 e3 c4 e3>
A浣犱綘
binary編碼=======================
<Buffer 41 60 60>
A``
end=======================
具體檔案資訊如下:
File { domain: null, _events: {}, _eventsCount: 0, _maxListeners: undefined, size: 160462, path: '/tmp/upload_c4ec9eb09f55db9e6d2efce19760e034', name: 'A浣犱綘.rar', type: 'application/octet-stream', hash: null, lastModifiedDate: 2019-01-04T02:09:54.482Z, _writeStream: WriteStream { _writableState: WritableState { objectMode: false, highWaterMark: 16384, finalCalled: false, needDrain: false, ending: true, ended: true, finished: true, destroyed: false, decodeStrings: true, defaultEncoding: 'utf8', length: 0, writing: false, corked: 0, sync: false, bufferProcessing: false, onwrite: [Function: bound onwrite], writecb: null, writelen: 0, bufferedRequest: null, lastBufferedRequest: null, pendingcb: 0, prefinished: true, errorEmitted: false, bufferedRequestCount: 0, corkedRequestsFree: [Object] }, writable: false, domain: null, _events: {}, _eventsCount: 0, _maxListeners: undefined, path: '/tmp/upload_c4ec9eb09f55db9e6d2efce19760e034', fd: null, flags: 'w', mode: 438, start: undefined, autoClose: true, pos: undefined, bytesWritten: 160462, closed: true } }