十年网站开发经验 + 多家企业客户 + 靠谱的建站团队
量身定制 + 运营维护+专业推广+无忧售后,网站问题一站解决
随着HTML5的普及,现在大部分浏览器都支持拖拽功能,今天我们要说的就是实现一套拖拽上传的功能(Angularjs+nodejs)。
网站建设哪家好,找成都创新互联!专注于网页设计、网站建设、微信开发、微信小程序、集团企业网站建设等服务项目。为回馈新老客户创新互联还提供了准格尔免费建站欢迎大家使用!
一、首先前端这款插件是基于AngularJS的,下面我们来看主要代码。
引入js:
html:
//上传文件的格式You may also import your own translationmemories(TMX)orAdd files...File Drag/Drop is not supported for this browserImage thumbnail://调整上传后图片顺序
js:
(function () { 'use strict'; angular.module('todoApp', ['ng-sortable','ngFileUpload']) .controller('UploadController', ['$scope','Upload', function ($scope,Upload) { $scope.showProgress = false; $scope.$watch('files', function () { $scope.upload($scope.files); });//监听files有改变就上传 $scope.upload = function (files) { if (files && files.length) { for (var i = 0; i < files.length; i++) { var file = files[i]; (function(i){ return Upload.upload({ url: '/upload', fields: {'username': $scope.username}, file: file }).progress(function (evt) { $scope.showProgress = true; var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);//上传百分比 console.log('progress: ' + progressPercentage + '% ' + evt.config.file.name); }).success(function (data, status, headers, config) { $scope.showProgress = true; var url = data.url; $scope.files[i].url = url; console.log('file ' + config.file.name + 'uploaded. Response: ', data); console.log("size:" + (config.file.size/1000).toFixed(2));//一个文件上传成功 }); })(i) } } }; }]) })();
二、然后是我们的后台代码:
1、app.js中设定上传文件缓存地址
var multiparty = require('connect-multiparty'); var config = require('./config').config; app.use(multiparty({ uploadDir: path.join(config.upload_dir) }));
2、上传代码:
exports.uploadImage = function (req, res, next) { /*if (!req.session || !req.session.user) { res.send({ status: 'forbidden' }); return; }*/ var file = req.files && req.files.file; if (!file) { res.send({ status: 'failed', message: 'no file' }); return; } //var uid = req.session.user._id.toString(); var uid = "stone"; var userDir = path.join(config.upload_dir, uid); ndir.mkdir(userDir, function (err) { if (err) { return next(err); } var filename = Date.now() + '_' + file.name; var savepath = path.resolve(path.join(userDir, filename)); if (savepath.indexOf(path.resolve(userDir)) !== 0) { return res.send({status: 'forbidden'}); } fs.rename(file.path, savepath, function (err) { if (err) { return next(err); } var url = '/upload/' + uid + '/' + encodeURIComponent(filename); res.send({ status: 'success', url: url }); }); }); };
三、调节图片顺序
加入Sortable插件用来拖拽调整上传图片的先后位置
1、引入js:
2、html代码:
//调整上传后图片顺序
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持创新互联。