프로젝트 에서이 방법을 가지고 있었지만 최근에는 고객에게 문제가있었습니다. 제 동료는이 방법이 작동하지 않았다고 말했습니다. 그래서 나는이 방법을 꺼내기 위해 하루를 보냈고 (조금 더 오래 걸렸다 고 생각합니다) 공유했습니다.
코드 및 테스트 사례 :
var http = require ( 'http'); var path = require ( 'path'); var fs = require ( 'fs'); 함수 postfile (fileKeyValue, req) {var boundaryKey = math.random (). toString (16); var enddata = '/r/n ----' + boundarykey + '-'; var files = new Array (); for (var i = 0; i <filekeyValue.length; i ++) {var content = "/r/n ----" + boundarykey + "/r/n" + "content-type : application/octet-stream/r/n" + "내용 내용 : form-data; name =/" " + filekeyvalue [i] .Urlkey +"/"/" ""/"" "/" + " PATH.BASENAME (fileKeyValue [i] .urlValue) + "/"/r/n " +"Content-Transfer-Encoding : Binary/r/n/r/n "; var contentbinary = new Buffer (Content, 'UTF-8'); // 인코딩이 ASCII 일 때 중국어가 차가워집니다. files.push ({contentBinary : contentBinary, filePath : fileKeyValue [i] .urlValue}); } var contentlength = 0; for (var i = 0; i <files.length; i ++) {var stat = fs.statsync (files [i] .filepath); ContentLength += 파일 [i] .ContentBinary.length; contentlength += stat.size; } req.setheader ( 'content-type', 'multipart/form-data; boundary =-' + boundarykey); Req.SetHeader ( 'ContentLength', ContentLength + Buffer.ByTelength (endData)); // 매개 변수 var fileIndex = 0; var doonefile = function () {req.write (files [fileIndex] .contentBinary); var filestream = fs.createreadstream (files [fileindex] .filepath, {buffersize : 4 * 1024}); filestream.pipe (req, {end : false}); filestream.on ( 'end', function () {fileIndex ++; if (fileIndex == files.length) {req.end (endData);} else {doonefile ();}}); }; if (fileIndex == files.length) {req.end (endData); } else {doonefile (); }} // 테스트 케이스 // http : //nodejs.org/api/http.html#http_http_request_options_callbackvar files = [urlkey : "file1", urlvalue : "e : //dfbf.jpg"}, urlkey : "urlkey :", urlValkey : " "e : //1.jpg"}, {urlkey : "file3", urlvalue : "e : // pro space inriate.mp3"}] var 옵션 = {호스트 : "로컬 호스트", 포트 : "8908", 메소드 : "post", 경로 : "/home/upload"} var req = http.request (opctions, console) res); console.log ( 'request :' + e.message); log (e);}); Console.log ( "완료");서버 테스트의 경우 MVC를 사용하여 홈 컨트롤러에 업로드 메소드를 작성하고 업로드 된 파일을 통과하고 하드 디스크에 저장하십시오.
큰 파일을 업로드하는 데 문제가있을뿐입니다. 서버를 구성 해야하는 것으로 추정되므로 지금은 걱정하지 마십시오.
서버 측 메소드 (홈 컨트롤러에서 쓰기)
[httppost] public string upload () {// httppostedfilebase file = this.request.files [ "file"]; //file.saveas(file.filename); foreach (this.request.files의 문자열 파일) {this.request.files [file] .saveas (@"e :/new 폴더/" + this.request.files [file] .filename); } return @"성공 경로 저장 : e :/new 폴더/"; }스크립트 실행 :
Node nodejspostfile.js
실행 결과 :