我是靠谱客的博主 酷炫荔枝,最近开发中收集的这篇文章主要介绍html5+nodejs多文件上传,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

最近学习文件上传,网上例子大多数是HTML5+python的,可惜本人不会python,暂时也没有时间和兴趣研究python,所以用node.js做后台接收文件上传。

写了一个简单的例子,在这里分享给大家。
项目目录如下:
|__fileupload
  |__public // 静态资源目录
     |__index.html
     |__upload.js
  |__ uploadfiles // 文件上传目录
  |__server.js // node.js服务器启动文件

  • node server.js 启动项目

index.html

<!DOCTYPE html>
<html>
<head>
    <title>使用XMLHttpRequest上传文件</title>
</head>
<body>
<form id="form1" enctype="multipart/form-data" method="post" action="upload.php">
    <div class="row">
        <label for="fileToUpload">Select a File to Upload</label>
        <input type="file" name="fileToUpload" id="fileToUpload" onchange="fileSelected();" multiple/>
    </div>
    <div id="fileName"></div>
    <div id="fileSize"></div>
    <div id="fileType"></div>
    <div class="row">
        <input type="button" onclick="uploadFile()" value="Upload" />
    </div>
    <div id="progressNumber"></div>
</form>

<script type="application/javascript" src="upload.js"></script>
</body>
</html>

upload.js

function fileSelected() {
    var file = document.getElementById('fileToUpload').files[0];
    if (file) {
        var fileSize = 0;
        if (file.size > 1024 * 1024)
            fileSize = (Math.round(file.size * 100 / (1024 * 1024)) / 100).toString() + 'MB';
        else
            fileSize = (Math.round(file.size * 100 / 1024) / 100).toString() + 'KB';

        document.getElementById('fileName').innerHTML = 'Name: ' + file.name;
        document.getElementById('fileSize').innerHTML = 'Size: ' + fileSize;
        document.getElementById('fileType').innerHTML = 'Type: ' + file.type;
    }
}

function uploadFile() {
    var xhr = new XMLHttpRequest();
    var fd = new FormData();
    fd.append("author", "connie");
    fd.append("name", "Html 5 File API/FormData");
    var files = document.getElementById('fileToUpload').files;

    // 单文件上传
    // fd.append("fileToUpload", files[0]);

    // 多文件上传
    for (key in files){
        fd.append("fileToUpload", files[key]);
    }


    /* event listners */
    xhr.upload.addEventListener("progress", uploadProgress, false);
    xhr.addEventListener("load", uploadComplete, false);
    xhr.addEventListener("error", uploadFailed, false);
    xhr.addEventListener("abort", uploadCanceled, false);
    /* Be sure to change the url below to the url of your upload server side script */
    xhr.open("POST", "upload");
    xhr.send(fd);
}

function uploadProgress(evt) {
    if (evt.lengthComputable) {
        var percentComplete = Math.round(evt.loaded * 100 / evt.total);
        document.getElementById('progressNumber').innerHTML = percentComplete.toString() + '%';
    }
    else {
        document.getElementById('progressNumber').innerHTML = 'unable to compute';
    }
}

function uploadComplete(evt) {
    /* This event is raised when the server send back a response */
    alert(evt.target.responseText);
}

function uploadFailed(evt) {
    alert("There was an error attempting to upload the file.");
}

function uploadCanceled(evt) {
    alert("The upload has been canceled by the user or the browser dropped the connection.");
}

server.js

/**
 * Created by Administrator on 2017/6/5.
 */
var express = require('express'),
    path = require('path'),
    app = express(),
    fs = require('fs'),
    multiparty = require('multiparty');  // FormData解析工具
var target_path;
var config = {
    upload_dir: 'uploadfiles'
}

// 引入静态文件代码
app.use(express.static(path.join(__dirname, 'public')));

// 文件上传url
app.post('/upload', function(req, res){
    var form = new multiparty.Form();
    form.parse(req, function (err, fields, files) {
        if (err){
           throw err
        }
        console.log(fields);
        console.log(files);
        // fields显示非文件类型的所有key、value值
        Object.keys(fields).forEach(function(name) {
            console.log('got field named ' + name);
        });

        for (key in files){
            files[key].forEach(function (file, index) {
                target_path = config.upload_dir + '/' + file.originalFilename;
                try {
                     // 读取缓存文件,同时写入所需上传的目录
                    fs.createReadStream(file.path).pipe(fs.createWriteStream(target_path));
                    console.log(file.originalFilename);
                    console.log('Upload completed!');
                    res.json({infor:"success"})
                } catch (err){
                    res.json({err:err})
                }
            })
        }
    });
});

app.listen(8080);
console.log('Listening on port 8080');

最后

以上就是酷炫荔枝为你收集整理的html5+nodejs多文件上传的全部内容,希望文章能够帮你解决html5+nodejs多文件上传所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(56)

评论列表共有 0 条评论

立即
投稿
返回
顶部