【问题标题】:JQuery JSON image upload to Node.JSJQuery JSON 图片上传到 Node.JS
【发布时间】:2014-09-22 07:30:41
【问题描述】:

我正在尝试将图像上传到 node.js,使用以下代码可以正常工作:

客户端:

$("#portrait-upload").change(function(e) {
  var data = e.target.files[0];

  $.ajax({
    url: "/upload",
    type: "POST",
    data: data,
    cache: false,
    processData: false,
    contentType: "multipart/form-data",
    success: function(response) {
      console.log(response);
    }
  });
});

服务器端:

if(req.url == "/upload"){
  var image = fs.createWriteStream("temp.jpg");

  req.on("data", function(chunk) {
    image.write(chunk);
    res.write("Data received.\n");
  });

  req.on("end", function() {
    image.end();
    res.end("Data reception ended.");
  });
}

此外,我想在服务器端读取文件名。显然,我无法从请求对象中读取它(至少我没有找到合适的方法)。所以我想用文件名和文件本身发布一个 JSON 对象 - 像这样:

{ filename : data.name, file: data }

但这显然不起作用 - 甚至可以将图像数据放入这样的 JSON 对象中并在服务器上读取它吗?

将文件名和图像文件本身传输到节点的更好方法是什么?

谢谢

【问题讨论】:

  • 您可以为此使用外部模块,例如formidable

标签: jquery node.js image upload


【解决方案1】:

您可以将文件名作为 GET 参数而不是 POST 发送。

【讨论】:

  • 非常感谢这个想法,这实际上是我这样做的,因为我还不想使用 express 或强大的 - 我现在想坚持使用“基本”节点模块。对于任何需要相同东西的人 - 这是客户端: $.get("/upload", { filename : image.name }).done(function(response) { console.log(response) });服务器端:在 http.createServer 回调内部: if((request.url).indexOf("/upload") > -1) { console.log(url.parse(request.url).query); }
猜你喜欢
  • 1970-01-01
  • 2022-01-15
  • 2015-01-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多