Javascript 不使用express将图像上载到node.js中的服务器

Javascript 不使用express将图像上载到node.js中的服务器,javascript,node.js,Javascript,Node.js,下面是我试图获取上传文件的服务器代码。然而,fs.writeFile不起作用,所以我假设我做错了什么 server.on('request', function(request, response){ .... if((pathArray[1] == "photos") && (pathArray[2] = "new")){ var imagesPath = './images'; upload

下面是我试图获取上传文件的服务器代码。然而,
fs.writeFile
不起作用,所以我假设我做错了什么

  server.on('request', function(request, response){
        ....
         if((pathArray[1] == "photos") && (pathArray[2] = "new")){
            var imagesPath = './images';
            uploadPhoto(response, imagesPath);
          }


       else if(path == '/document/save'){
            console.log("path: " + path);

            var body = '';

            request.on('data', function(data){
                body += data;
            });

            request.on('end', function() {
                var note = querystring.parse(body);
                console.log("Body data: " + note);
                var newPath = "./images/myimage.jpg";
                fs.writeFile( newPath, body, function (err) {
                     if (err) throw err;
                 });
            });




        }   
这是我的表单HTML,如果它对任何人都有帮助:

 function uploadPhoto(response, imageLoc){  

    response.writeHead(200, {
        'Content-Type': 'text/html' 
    });

    response.write('<html><body>');     
    response.write('<div class="uploadFile">');
    response.write('<link rel="stylesheet" type="text/css" href="style.css">');
    response.write('<form action =/document/save>');
    response.write('<method = "post">');
    response.write('<enctype="multipart/form-data">');
    response.write('<label for="name">Upload new photo</label>');
    response.write('<br></br>');
    response.write('<input type="file" name="name">');
    response.write('<br></br>');
    response.write('<button type="submit">Upload</button>');
    response.write('</div>');

    response.write('</body></html>');
    response.write('</form>');


    response.end();
}
函数上传照片(响应,imageLoc){
书面答复(200{
“内容类型”:“文本/html”
});
回答。写(“”);
回答。写(“”);
回答。写(“”);
回答。写(“”);
回答。写(“”);
回答。写(“”);
回复。写(‘上传新照片’);
响应。写入(“

”); 回答。写(“”); 响应。写入(“

”); 响应。写入(“上传”); 回答。写(“”); 回答。写(“”); 回答。写(“”); response.end(); }
上传文件后,url转到/document/save/uploadImage.jpg。但是当我试图读取图像的内容(“body”)以将图像保存到文件夹中并显示它时,请求对象的内容似乎是空的


如何在没有express的情况下使用
node.js
,或者使用我现有的任何外部库来获取图像的内容?写入二进制文件时,
fs.writeFile
是一个好函数吗

必须考虑的是,从上传接收到的数据具有以下格式:

------WebKitFormBoundary9BhXe3lt2UddCDz9
Content-Disposition: form-data; name="document"; filename="globeSS.jpg"
Content-Type: image/jpeg

ÿØÿà JFIF   d d  ÿì Ducky     d  ÿá
//[binary binary binary...]
Ï[leñnœ“}ÛOyŠVÑ0êãXÂ}Ö'±”É iÉöÚ$GTQ7äŽø
uÚ_êÍòXgV¿Õ=€q`]a­KRÐÀ
ò<ÿÙ
------WebKitFormBoundary9BhXe3lt2UddCDz9--

这应该适用于所有浏览器(请注意,internet explorer不使用
----WebkitFormBoundary
限制其数据,而是使用其他内容(我认为只有
----
,但我忘记了。)

fs.writeFile()调用属于request.on('end')处理程序。可以在request.on('end')中使用fs.writeFile()处理程序保存的图像是15字节,而不是0,0仍然不是我上传的图像。如果您可以在console.log中看到数据,请确保您正在写入二进制文件fs.writeFile(newPath,注意,{encoding:“binary”},…我在控制台中看不到数据。它只是打印对象。它仍然使用编码二进制文件保存15字节的图像。请使用note=decodeURIComponent(body)和log()和write()进行尝试同样的变量以避免疯狂。我的数据以二进制形式返回时遇到了类似的问题,你能看一下吗?Thanks@JDT很抱歉,我甚至不记得这是怎么回事。我将无法帮助您无需担心,正在处理二进制视频数据并保存到blockblob,并且不确定这是否是webkitform问题
request.setEncoding('binary'); 

//Grabbing all data from the image
var body = ''
var binaryEnd; //gets the string that indicates the location of the end of the binary file
var first = true;
request.on('data', function(data) {
    if(first)
        binaryEnd = data.toString().substring(0, data.toString().indexOf('\n')-1);
    first = false;
    body += data
});

//Dealing with the image once we have everything 
request.on('end', function() {      

    var note = querystring.parse(body, '\r\n', ':')
    console.log(note)

    //making sure than an image was submitted 
    if (note['Content-Type'].indexOf("image") != -1)
    {   
        //get the filename 
        var fileInfo = note['Content-Disposition'].split('; ');
        for (value in fileInfo){
            if (fileInfo[value].indexOf("filename=") != -1){
                fileName = fileInfo[value].substring(10, fileInfo[value].length-1); 

                if (fileName.indexOf('\\') != -1)
                    fileName = fileName.substring(fileName.lastIndexOf('\\')+1);
                console.log("My filename: " + fileName); 
            }   
        }

                    //Get the type of the image (eg. image/gif or image/png)
        var entireData = body.toString();           
        var contentTypeRegex = /Content-Type: image\/.*/;

        contentType = note['Content-Type'].substring(1); 

                    //Get the location of the start of the binary file, 
                    //which happens to be where contentType ends
        var upperBoundary = entireData.indexOf(contentType) + contentType.length; 
        var shorterData = entireData.substring(upperBoundary); 

                    //replace trailing and starting spaces 
        var binaryDataAlmost = shorterData.replace(/^\s\s*/, '').replace(/\s\s*$/, '');

                    //Cut the extra things at the end of the data (Webkit stuff)
        var binaryData = binaryDataAlmost.substring(0, binaryDataAlmost.indexOf(firstLine));        

                    //Write to a file 
        fs.writeFile('./images/' + fileName  , binaryData, 'binary', function(err)
        {
                            //forward to another location after writing data 
            response.writeHead(302, {
                'location':'/index.html'
            });
            response.end();
        });
    }
    else
        respond(404, "Please input an image", response); 
});