【问题标题】:Creating a HTTP Server in Node.js service POST with file使用文件在 Node.js 服务 POST 中创建 HTTP 服务器
【发布时间】:2015-05-30 18:40:48
【问题描述】:

我想将订单发送到带有参数的 POST 请求,格式为 JPG 文件。

我在 4.4.1 版本中使用 HttpClient

部分 Java 代码如下所示:

    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
        File file = new File("path_to_jpg");
        HttpPost post = new HttpPost("http://localhost:1337/uploadJPG");
        FileBody fileBody = new FileBody(file);

        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        builder.addPart("upfile", fileBody);
        HttpEntity entity = builder.build();

        post.setEntity(entity);
        HttpResponse response = httpclient.execute(post);
        System.out.println(response.getEntity().getContent());

    } finally {
        httpclient.close();
    }

next at "http://localhost:1337/uploadJPG" 想让 nodeJS 有一个服务器来处理 JPG 文件

服务端代码nodeJS的思路:

var http = require('http'),
fs = require('fs'),
server = http.createServer( function(req, res) {

    if (req.method == 'POST') {

        //process file JPG

        res.writeHead(200, {'Content-Type': 'text/html'});
        res.end('processed JPG');
    }
});

port = 1337;
host = '127.0.0.1';
server.listen(1337, '127.0.0.1');
console.log('Listening at http://' + '127.0.0.1' + ':' + 1337);

现在我的问题是,如何在 NodeJS 中创建这样的服务,它将文件保存为 jpg?

【问题讨论】:

    标签: java javascript node.js httpclient


    【解决方案1】:

    不确定您是否使用Express,但如果您使用,您可以使用像Multer 这样的中间件,这使得处理MultiPart 数据和文件变得非常简单。

    【讨论】:

    • Multer 需要“multipart/form-data”类型,但我的 .jpg 文件类型为:“application / octet-stream” 此外,multer 不需要文件已经在硬盘上?服务器的目标将位于与 Java 应用程序不同的位置
    猜你喜欢
    • 2014-09-22
    • 1970-01-01
    • 2012-04-14
    • 1970-01-01
    • 2012-10-11
    • 1970-01-01
    • 1970-01-01
    • 2011-08-28
    • 1970-01-01
    相关资源
    最近更新 更多