将图像从 JQuery 上传到 Node JS

2024-05-03

我需要从我的网站上传图像文件HTML页。但是,我不会使用form标签,因为还有其他form稍后将用于将数据传递到服务器的字段(文本字段、复选框等)。

我的后端在Node JS。我想要的只是从Node Js结尾。我怎样才能做到这一点

HTML

<div class="container">
    <div class="row">
      <div class="col-xs-12">
        <div class="panel panel-default">
          <div class="panel-body">
            <span class="glyphicon glyphicon-cloud-upload"></span>
            <h2>File Uploader</h2>
            <h4>coligo.io</h4>
            <div class="progress">
              <div class="progress-bar" role="progressbar"></div>
            </div>
            <button class="btn btn-lg upload-btn" type="button">Upload File</button>
          </div>
        </div>
      </div>
    </div>
  </div>
 <input id="upload-input" type="file" name="uploads" multiple="multiple"></br>

JQuery

$('.upload-btn').on('click', function (){
    $('#upload-input').click();
    $('.progress-bar').text('0%');
    $('.progress-bar').width('0%');
});

$('#upload-input').on('change', function(){

  var files = $(this).get(0).files;

  if (files.length > 0){
    // create a FormData object which will be sent as the data payload in the
    // AJAX request
    var formData = new FormData();
       // loop through all the selected files and add them to the formData object
    for (var i = 0; i < files.length; i++) {
      var file = files[i];
var tmppath = URL.createObjectURL(event.target.files[0]);
      // add the files to formData object for the data payload
      formData.append('uploads', tmppath);

    }
    $.ajax({
      url: '/myp/imgup',
      type: 'POST',
      data: formData,
      processData: false,
      contentType: false,
      success: function(data){
          console.log('upload successful!\n' + data);
      },
      xhr: function() {
        // create an XMLHttpRequest
        var xhr = new XMLHttpRequest();

        // listen to the 'progress' event
        xhr.upload.addEventListener('progress', function(evt) {

          if (evt.lengthComputable) {
            // calculate the percentage of upload completed
            var percentComplete = evt.loaded / evt.total;
            percentComplete = parseInt(percentComplete * 100);

            // update the Bootstrap progress bar with the new percentage
            $('.progress-bar').text(percentComplete + '%');
            $('.progress-bar').width(percentComplete + '%');

            // once the upload reaches 100%, set the progress bar text to done
            if (percentComplete === 100) {
              $('.progress-bar').html('Done');
            }

          }

        }, false);

        return xhr;
      }
    });

  }
});

NODE JS

router.post('/imgup', function(req, res){
    console.log(' File name '+req.files.upload);

});

我已经尝试了好几天了,但没有成功。有人可以帮我吗。


使用的示例multer module:

var express =   require("express");
var multer  =   require('multer');
var app         =   express();
app.get('/',function(req,res){
      res.sendFile(__dirname + "/index.html");
});


var storage =   multer.diskStorage({
  destination: function (req, file, callback) {
    callback(null, './uploads');
  },
  filename: function (req, file, callback) {
    callback(null, file.fieldname + '-' + Date.now());
  }
});

app.post('/api/file',function(req,res){
    var upload = multer({ storage : storage}).single('userFile');
    upload(req,res,function(err) {
        if(err) {
            return res.end("Error uploading file.");
        }
        res.end("File is uploaded");
    });
});

app.listen(3000,function(){
    console.log("Working on port 3000");
});

一个例子formidable module:

var formidable = require('formidable'),
http = require('http'),
util = require('util');

http.createServer(function(req, res) {
  if (req.url == '/upload' && req.method.toLowerCase() == 'post') {
    // parse a file upload
    var form = new formidable.IncomingForm();

    form.parse(req, function(err, fields, files) {
      if (err)
          do-smth; // process error

      // Copy file from temporary place
      // var fs = require('fs');
      // fs.rename(file.path, <targetPath>, function (err) { ... });         

      // Send result on client
      res.writeHead(200, {'content-type': 'text/plain'});
      res.write('received upload:\n\n');
      res.end(util.inspect({fields: fields, files: files}));
    });

    return;
  }

  // show a file upload form
  res.writeHead(200, {'content-type': 'text/html'});
  res.end(
    '<form action="/upload" enctype="multipart/form-data" method="post">'+
    '<input type="text" name="title"><br>'+
    '<input type="file" name="upload" multiple="multiple"><br>'+
    '<input type="submit" value="Upload">'+
    '</form>'
  );
}).listen(8080);

摘自Node.js - 上传文件 https://web.archive.org/web/20170816202112/https://stackoverflow.com/documentation/node.js/4080/file-upload。原作者是Iceman https://stackoverflow.com/users/6237235/iceman, 艾康·莫格瓦伊 https://stackoverflow.com/users/6121703/aikon-mogwai and Mikhail https://stackoverflow.com/users/5526354/mikhail。归属详细信息可以在贡献者页面 https://web.archive.org/web/2/https://stackoverflow.com/documentation/contributors/topic/4080。来源已获得许可抄送-SA 3.0 https://creativecommons.org/licenses/by-sa/3.0/并且可以在文档存档 https://archive.org/details/documentation-dump.7z。参考主题 ID:4080。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将图像从 JQuery 上传到 Node JS 的相关文章

随机推荐

  • 由于参数中有空格,Bash 脚本因未知选项而失败

    我正在尝试运行 aws create lambda 函数 事情的经过如下 eval aws lambda create function function name FUNCTION NAME runtime RUNTIME role RO
  • 如何使用 ActionText 显示嵌入视频

    我正在尝试在 Rails 6 上使用 ActionText 显示嵌入式视频 无论是在 WYSIWYG Trix 中还是在渲染的内容中 但是 ActionText 渲染器会过滤所有原始 html 代码 并强制我使用 JS 在渲染内容中显示 i
  • 从节点内部开始一条边

    digraph foo a label
  • Linq 警告

    Linq 是 NET 的一个很棒的补充 我发现它在很多情况下都对我很有帮助 尽管我才刚刚开始学习如何使用 Linq 然而 在阅读有关 Linq 的文章时 我发现开发人员需要留意一些微妙的事情 否则可能会导致麻烦 我已经添加了一个明确的警告
  • Bash或Python,当打印字符到终端时,如何更改固定位置的字符?

    我想知道的事情应该是非常 基本 的 但这是我脑海中很长一段时间的问题 不知道窍门在哪里 假设在一个耗时的程序中 或者bash or Python 我必须打印出运行时的进度百分比 基本上我想打印1 一段时间后 我打印2 等等 我想要 2 完全
  • Boost C++ 和 Android 3

    我尝试用谷歌和SO搜索 到目前为止 我只能找到相互矛盾的信息 如果 Boost 和 Android 结合太难 也许有替代品 我对 smart ptr 线程 函数 lexical cast string algo 和容器特别感兴趣 任何意见都
  • 如何在android中使用jquery和phonegap打开pdf文件?

    最近我正在为 Android 构建一个应用程序 我正在使用phonegap 来做同样的事情 一切都运行良好 除了一个问题 即我无法在 android 中使用 jquery 打开 pdf 文件 我已经尝试了很多做同样的事情 但我无法做到这一点
  • 从主目录隐藏八度工作区文件

    我想更改文件octave workspace从我的主目录中 只需将其重命名为 octave workspace 如何设法使 Octave 识别具有此新名称的工作区文件 或创建一个新文件 Thanks 这就是该组织的目的octave core
  • 哪种 ZeroMQ 模式最适合异步套接字对?

    我有一个服务器 在亚马逊上运行 和一个连接到它的客户端 建立连接后 客户端和服务器仅相互通信并发送消息 e g 1 Client gt Server 2 Client gt Server 3 Client lt Server 4 Clien
  • Android:向系统添加自定义字体

    我知道如何在应用程序中使用自定义字体 但我想做的是在系统范围内添加自定义字体 就像在 Windows 上添加新字体一样 如果没有官方的方法 我应该阅读android源代码的哪个模块 我必须更改 android 源代码并构建它以支持自定义字体
  • 运行添加迁移时无法加载程序集 Microsoft.EntityFrameworkCore.Design

    我使用以下 csproj 创建了一个类库项目
  • 如何将 JSON 响应映射到 Angular 4 中的模型

    我已经尝试了很多 但无法将端点响应映射到我的模型 我正在使用 HttpClient 和 Angular4 我从服务中获取了数据 但它没有正确映射到我的模型类 我有以下 JSON 服务正在返回 result id 1 type User co
  • Android 中 Activity 之间的对象共享

    您好 我有一个关于在整个应用程序中传递对象的问题 假设我想在整个应用程序中拥有一个大的自定义对象 该对象将被多个活动和服务使用 我一开始做的就是这样的 首先 我创建了一个 Application 类并定义了一个单例对象 public cla
  • 代码签名身份 <名称> 与任何有效的、未过期的代码签名证书不匹配

    我希望有人能帮我解决这个令人抓狂的问题 我和我的朋友正在开发一个 mac 商店应用程序 托管在 github 上 一个月前 我们使用他的开发中心帐户从他的机器上发布了该应用程序 我最近将源代码从 github 拉到我的机器上 以进行更新 但
  • 使用 php5-geoip 和 Maxmind 数据库获取 IPv6 支持

    我按照这些相同的步骤进行了 geoip 设置 http php net manual en geoip setup php http php net manual en geoip setup php wget http geolite m
  • Spring 3.1 MVC - 表单处理工作流程最佳实践

    目前我正在尝试了解 Spring MVC 3 1 中表单提交 验证 错误处理的正确工作流程 不 我有一些问题 保留表单错误 通过重定向绑定模型的正确方法是什么 是否有内置方法 我还没有找到 我知道我可以使用 Spring 表单标签和 JSR
  • 选择给定日期范围内的所有月份,包括值为 0 的月份

    我正在尝试编写一个 MySQL 查询来获取给定日期之间所有月份的每月平均值 我的想法是这样的 查询 类似 SELECT AVG value1 as avg value 1 AVG value2 as avg value 2 MONTH sa
  • JavaScript“可写”属性描述符如何工作?

    为什么 JavaScript 可写 属性描述符不禁止任何属性更改 例如 var TheDarkKnight Object create Superhero name value Batman writable false TheDarkKn
  • ngOnChange 不存储 previousValue 属性

    Angular2 RC4 angularfire2 2 0 0 beta 2 在我的子组件中我无法获取changes posX previousValue存储任何东西 父级 html 的片段 inside ngfor loop posX c
  • 将图像从 JQuery 上传到 Node JS

    我需要从我的网站上传图像文件HTML页 但是 我不会使用form标签 因为还有其他form稍后将用于将数据传递到服务器的字段 文本字段 复选框等 我的后端在Node JS 我想要的只是从Node Js结尾 我怎样才能做到这一点 HTML d