使用node.js在Azure文件存储中上载文件

时间:2015-12-17 10:12:17

标签: node.js azure azure-storage azure-mobile-services azure-storage-files

我们正在尝试创建一个Web服务,使用node.js服务将文件上传到Azure文件存储。

以下是node.js服务器代码。

exports.post = function(request, response){
var shareName = request.headers.sharename;
var dirPath = request.headers.directorypath;
var fileName = request.headers.filename;

var body;
var length;

request.on("data", function(chunk){
    body += chunk;
    console.log("Get data");
});


request.on("end", function(){
    try{
        console.log("end");
        var data = body;
        length = data.length;

console.log(body); // This giving the result as undefined
console.log(length);

        fileService.createFileFromStream(shareName, dirPath, fileName, body, length, function(error, result, resp) {
            if (!error) {
                // file uploaded
                response.send(statusCodes.OK, "File Uploaded");
            }else{
                response.send(statusCodes.OK, "Error!");
            }
        });

    }catch (er) {
response.statusCode = 400;
return res.end('error: ' + er.message);
}

});

}

以下是我们上传文件的客户。

private static void sendPOST() throws IOException {
    URL obj = new URL("https://crowdtest-fileservice.azure-mobile.net/api/files_stage/");
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    con.setRequestMethod("POST");
    con.setRequestProperty("sharename", "newamactashare");
    con.setRequestProperty("directorypath", "MaheshApp/TestLibrary/");
    con.setRequestProperty("filename", "temp.txt");


    Path path = Paths.get("C:/Users/uma.maheshwaran/Desktop/Temp.txt");
    byte[] data = Files.readAllBytes(path);

    // For POST only - START
    con.setDoOutput(true);
    OutputStream os = con.getOutputStream();
    os.write(data);
    os.flush();
    os.close();
    // For POST only - END

    int responseCode = con.getResponseCode();
    System.out.println("POST Response Code :: " + responseCode);

    if (responseCode == HttpURLConnection.HTTP_OK) { // success
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
            System.out.println(inputLine);
        }
        in.close();

        // print result
        System.out.println(response.toString());
    } else {
        BufferedReader br = new BufferedReader(new InputStreamReader(con.getErrorStream()));
        String line = "";
        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }
        System.out.println("POST request not worked");
    }
}

显示错误

  

请求'POST / api / files_stage /'已超时。这可能是   由无法写入响应的脚本或其他原因引起的   无法及时从异步调用返回。

已更新:

我也试过下面的代码。

  var body = new Object();
  body = request.body;
  var length = body.length;

  console.log(request.body);
  console.log(body);
  console.log(length);

    try {
        fileService.createFileFromStream(shareName, dirPath, fileName, body, length, function(error, result, resp) {
            if (!error) {
                // file uploaded
                response.send(statusCodes.OK, "File Uploaded");
            }else{
                response.send(statusCodes.OK, "Error!");
            }
        });
    } catch (ex) {
            response.send(500, { error: ex.message });
    }

但面对问题

  

{“error”:“函数createFileFromStream的参数流应该是   一个对象“}

我是node.js的新手。请帮我解决这个问题。

5 个答案:

答案 0 :(得分:8)

这里有几个问题。让我们一个接一个地看看它们。

<强> 1。在Java客户端中,您不能只将二进制数据转储到Azure移动服务连接中。

原因是Azure移动服务有两个主体解析器,无论如何都能确保为您解析请求主体。 因此,虽然您可以通过指定不常见的内容类型来遍历Express正文解析器,但您仍然会通过天真地假设它是UTF-8字符串来点击Azure主体解析器,这会破坏您的数据流。

因此,唯一的选择是通过指定无法处理的内容类型跳过Express解析器,然后通过使用Base64编码对二进制数据进行编码来播放Azure解析器。

因此,在Java客户端替换

Path path = Paths.get("C:/Users/uma.maheshwaran/Desktop/Temp.txt");
byte[] data = Files.readAllBytes(path);

con.setRequestProperty("content-type", "binary");    
Path path = Paths.get("C:/Users/uma.maheshwaran/Desktop/Temp.txt");
byte[] data = Files.readAllBytes(path);
data = Base64.getEncoder().encode(data);

如果您不在Java 8上,请将java.util.Base64编码器替换为您有权访问的任何其他Base64编码器。

<强> 2。您尝试使用的createFileFromStream Azure存储api功能需要一个流。

同时,手动解析请求主体时可以获得的最佳结果是字节数组。不幸的是,Azure移动服务使用NodeJS版本0.8,这意味着没有简单的方法来构建来自字节数组的可读流,并且您必须组装适合Azure存储API的自己的流。一些胶带和stream@0.0.1应该没问题。

var base64 = require('base64-js'),
    Stream = require('stream'),
    fileService = require('azure-storage')
        .createFileService('yourStorageAccount', 'yourStoragePassword');

exports.post = function (req, res) {
    var data = base64.toByteArray(req.body),
        buffer = new Buffer(data),
        stream = new Stream();
        stream['_ended'] = false;
        stream['pause'] = function() {
            stream['_paused'] = true;
        };
        stream['resume'] = function() {
            if(stream['_paused'] && !stream['_ended']) {
                stream.emit('data', buffer);
                stream['_ended'] = true;
                stream.emit('end');
            }
        }; 
    try {
        fileService.createFileFromStream(req.headers.sharename, req.headers.directorypath, 
            req.headers.filename, stream, data.length, function (error, result, resp) {
                res.statusCode = error ? 500 : 200;
                res.end();
            }
        );
    } catch (e) {
        res.statusCode = 500;
        res.end();
    }
};

这些是此示例所需的依赖项。

"dependencies": {   
    "azure-storage": "^0.7.0",
    "base64-js": "^0.0.8",
    "stream": "0.0.1"
}

如果在服务的package.json中指定它们不起作用,您可以随时转到此link并通过控制台手动安装它们。

cd site\wwwroot
npm install azure-storage
npm install base64-js
npm install stream@0.0.1

第3。要增加1Mb的默认上传限制,请为您的服务指定MS_MaxRequestBodySizeKB。

MS_MaxRequestBodySizeKB

请记住,因为您要将数据作为Base64编码传输,因此您必须考虑此开销。因此,要支持上传大小不超过20Mb的文件,您必须将MS_MaxRequestBodySizeKB设置为大约20 * 1024 * 4/3 = 27307.

答案 1 :(得分:3)

当请求到达exports.post中定义的函数时,整个请求已经存在,因此您不需要缓冲它。您可以通过编写下面代码的内容来简化它。

exports.post = function(request, response){
    var shareName = request.headers.sharename;
    var dirPath = request.headers.directorypath;
    var fileName = request.headers.filename;

    var body = request.body;
    var length = body.length;

    console.log(length);

    try {
        fileService.createFileFromText(shareName, dirPath, fileName, body, function(error, result, resp) {
            if (!error) {
                // file uploaded
                response.send(statusCodes.OK, "File Uploaded");
            } else {
                response.send(statusCodes.OK, "Error!");
            }
        });
    } catch (ex) {
        response.send(500, { error: ex.message });
    }
}

答案 2 :(得分:3)

我发现最简单的方法是使用pkgcloud来抽象云提供商之间的差异,并提供一个干净的界面来上传和下载文件。它使用流,因此实现也是内存效率。

var pkgcloud = require('pkgcloud')
var fs = require('fs')
var client = pkgcloud.storage.createClient({
  provider: 'azure',
  storageAccount: 'your-storage-account',
  storageAccessKey: 'your-access-key'
});

var readStream = fs.createReadStream('a-file.txt');
var writeStream = client.upload({
  container: 'your-storage-container',
  remote: 'remote-file-name.txt'
});

writeStream.on('error', function (err) {
  // handle your error case
});

writeStream.on('success', function (file) {
  // success, file will be a File model
});

readStream.pipe(writeStream);

答案 3 :(得分:3)

我们可以在SO How to send an image from Android client to Node.js server via HttpUrlConnection?上利用这个线程的答案,它创建一个自定义中间件来将上传文件内容放到缓冲区数组中,然后我们可以使用createFileFromText()将文件存储在Azure中存储

以下是代码段:

function rawBody(req, res, next) {
    var chunks = [];

    req.on('data', function (chunk) {
        chunks.push(chunk);
    });

    req.on('end', function () {
        var buffer = Buffer.concat(chunks);

        req.bodyLength = buffer.length;
        req.rawBody = buffer;
        next();
    });

    req.on('error', function (err) {
        console.log(err);
        res.status(500);
    });
}
router.post('/upload', rawBody,function (req, res){

    fileService.createShareIfNotExists('taskshare', function (error, result, response) {
        if (!error) {
            // if result = true, share was created.
            // if result = false, share already existed.
            fileService.createDirectoryIfNotExists('taskshare', 'taskdirectory', function (error, result, response) {
                if (!error) {
                    // if result = true, share was created.
                    // if result = false, share already existed.
                    try {
                        fileService.createFileFromText('taskshare', 'taskdirectory', 'test.txt', req.rawBody, function (error, result, resp) {
                            if (!error) {
                                // file uploaded
                                res.send(200, "File Uploaded");
                            } else {
                                res.send(200, "Error!");
                            }
                        });
                    } catch (ex) {
                        res.send(500, { error: ex.message });
                    }

                }
            });
        }
    });

})
router.get('/getfile', function (req, res){
    fileService.createReadStream('taskshare', 'taskdirectory', 'test.txt').pipe(res);
})

答案 4 :(得分:0)

有几件事:

<强> 1。 createFileFromText可以使用纯文本。但是对于那些二进制内容来说它会失败,因为它使用UTF-8编码。

您可能希望在Saving blob (might be data!) returned by AJAX call to Azure Blob Storage creates corrupt image

中引用blob的类似问题

<强> 2。 createFileFromStreamcreateWriteStreamToExistingFile \ createWriteStreamToNewFile Azure存储API可能是有用的功能。

请注意,这些API是流的目标。您需要将请求正文中的缓冲区/字符串转换为流。您可以参考How to wrap a buffer as a stream2 Readable stream?

createFileFromStream

fileService.createFileFromStream(req.headers.sharename, 
  req.headers.directorypath, 
  req.headers.filename, 
  requestStream, 
  data.length, 
  function (error, result, resp) {
    res.statusCode = error ? 500 : 200;
    res.end();
  }
);

createWriteStreamToNewFile

var writeStream = fileService.createWriteStreamToNewFile(req.headers.sharename, 
  req.headers.directorypath, 
  req.headers.filename, 
  data.length);

requestStream.pipe(writeStream);

第3。您的代码中存在几个问题

console.log(body); // This giving the result as undefined

原因是您定义var body并且它是undefined。代码body += chunk仍会使body未定义。

fileService.createFileFromStream(shareName, dirPath, fileName, body, length, function(error, result, resp) {
  if (!error) {
    // file uploaded
    response.send(statusCodes.OK, "File Uploaded");
  }else{
    response.send(statusCodes.OK, "Error!");
  }
});

createFileFromStream发生错误时,它也可能是网络传输中的错误,您可能还想返回错误代码而不是statusCodes.OK