天天看点

bootstrap多文件上传和单文件上传开发环境bootstrap + .net 前后端一体

开发环境bootstrap + .net 前后端一体

多文件上传

1.引用的前端文件包括https://download.csdn.net/download/oneofironlady/21068025

2.具体调用:

HTML:(多文件和单文件上传公用一个静态界面)styles.imageuploader.css

<div id="fileDiv" class="htmleaf-container" style="display:none; position: absolute;width: 50%;height: 50%;overflow: auto;bottom: 25%;left: 20%;background-color: rgb(252, 252, 252);z-index: 9;font-size:20px">
                <button id="close" class="btn btn-default" type="button" onclick="showFilemdb(false,'fileDiv')" style="background-color: rgb(252, 252, 252);border: none;font-size: 20px;float: right;">
                    <i class="glyphicon glyphicon-remove"></i></button>
                <section role="main" class="l-main" style="margin-top:50px;margin-bottom:50px">
                    <div id="loadmdb" class="uploader__box js-uploader__box l-center-box">
                        <form action="#" method="post">
                            <div class="uploader__contents">
                                <label class="button button--secondary" for="fileinput">请选择文件</label>
                                <input id="fileinput" class="uploader__file-input" type="file" />
                            </div>
                            <!--<input class="button button--big-bottom" type="submit" value="Upload Selected Files" />-->
                        </form>
                    </div>
                </section>
            </div>
       ```
           

JS:选中文件、校验、上传等

1、多文件上传 :jquery.imageuploader.js

说明:在调用界面需要初始化,初始化代码如下:

```javascript
 var upload;
	 var newId = '';//添加id
	$(function () {
		if (operateAll == 'add') {
			newId = uuid();
		} else {
			newId = idAll;
		}
		//文件上传插件初始化
		upload = $('.js-uploader__box').uploader({
			'selectButtonCopy': '请选择或拖拽文件',
			'instructionsCopy': '你可以选择或拖拽多个文件',
			'submitButtonCopy': '上传选择的文件',
			'furtherInstructionsCopy': '你可以选择或拖拽更多的文件',
			'secondarySelectButtonCopy': '选择更多的文件',
			'badFileTypeMessage': '上传格式不符,上传为jpg, png,jpeg !',
			'ajaxUrl': '../ajaxWeb/assetAjax.ashx?cmd=6&id=' + newId
		});
		if (operateAll != 'add') {
			$("#qrDiv").show();
			getResultById();

			$("#addId").text("修改");
			if (operateAll == 'detail') {
				$("#addId").text("详情");
				$("#fileButton").text("查看图片");
				disable();
			} else {
				$("#assetCode").attr("disabled", "true");
				$("#assetName").attr("disabled", "true");
				$("#buyTime").attr("disabled", "true");
			}
		}
	});
	//生成UUID
    function uuid() {
    var s = [];
    var hexDigits = "0123456789abcdef";
    for (var i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    s[14] = "4";
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);
    s[8] = s[13] = s[18] = s[23] = "";
    var uuid = s.join("");
    return uuid;
    }
           

单文件上传

var newId = '';//添加id
		var options = [];
		var dommdb;
		var state;
		//初始化
		$(function () {
			newId = uuid();
			getTable();
			index = 0;
			options = $.extend({
				submitButtonCopy: '上传选择的文件',
				selectButtonCopy: '请选择或拖拽文件',
				dropZone: $('#loadmdb'),
				fileTypeWhiteList: ['mdb'],
				badFileTypeMessage: '上传格式不符,上传为mdb !',
				ajaxUrl: '../ajaxWeb/uploadWorkAjax.ashx?cmd=1&id=' + newId,
				testMode: false
			}, options);

			state = {
				fileBatch: [],
				isUploading: false,
				isOverLimit: false,
				listIndex: 0
			};

			// create DOM elements
			dommdb = {
				uploaderBox: $('#loadmdb'),
				submitButton: $('<button class="js-uploader__submit-button uploader__submit-button uploader__hide">' +
					options.submitButtonCopy + '<i class="js-uploader__icon glyphicon"></i></button>'),
				selectButton: $('<input style="height: 0; width: 0;" id="fileinput' + index + '" type="file" multiple class="js-uploader__file-input uploader__file-input">' +
					'<label for="fileinput' + index + '" style="cursor: pointer;" class="js-uploader__file-label uploader__file-label">' +
					options.selectButtonCopy + '</label>'),
				fileList: $('<ul class="js-uploader__file-list uploader__file-list"></ul>'),
				contentsContainer: $('<div class="js-uploader__contents uploader__contents"></div>')
			};

			// empty out whatever is in there
			dommdb.uploaderBox.empty();

			// create and attach UI elements
			setupDOMmdb(dommdb);

			// set up event handling
			bindUIEventsmdb();
		});
		//上传文件
		function fileButtonClick() {
			showFilemdb(true, 'fileDiv');//调用弹窗形式,未找到在哪限制只可选择图片


		}
		//图片上传弹框
		function showFilemdb(type, id) {
			if (type) {
				$("#" + id).show();
			} else {
				$("#" + id).hide();
			}
		}
		 
		//生成UUID
		function uuid() {
			var s = [];
			var hexDigits = "0123456789abcdef";
			for (var i = 0; i < 36; i++) {
				s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
			}
			s[14] = "4";
			s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);
			s[8] = s[13] = s[18] = s[23] = "";
			var uuid = s.join("");
			return uuid;
		}

		//上传的相关
		function setupDOMmdb(dommdb) {
			dommdb.contentsContainer
				.append(dommdb.selectButton);
			dommdb.uploaderBox
				.append(dommdb.fileList)
				.append(dommdb.contentsContainer)
				.append(dommdb.submitButton)
		}

		function bindUIEventsmdb() {
			
			options.dropZone.on('dragover dragleave', function (e) {
				e.preventDefault();
				e.stopPropagation();
			});
			$.event.props.push('dataTransfer');
			options.dropZone.on('drop', selectFilesHandlermdb);
			
			dommdb.selectButton.on('click', function () { $('#loadmdb').value = null; });
			dommdb.selectButton.on('change', selectFilesHandlermdb);
			
			dommdb.submitButton.on('click', uploadSubmitHandlermdb);
			
			dommdb.uploaderBox.on('click', '.js-upload-remove-button', removeItemHandlermdb);
			
			if (options.testMode) {
				options.dropZone.on('uploaderTestEvent', function (e) {
					switch (e.functionName) {
						case 'selectFilesHandler':
							selectFilesHandlermdb(e);
							break;
						case 'uploadSubmitHandler':
							uploadSubmitHandlermdb(e);
							break;
						default:
							break;
					}
				});
			}
		}

		function addItemmdb(file) {
			var fileName = cleanNamemdb(file.name);
			var fileSize = file.size;
			var id = state.listIndex;
			var lastdate = file.lastModifiedDate;
			var sizeWrapper;
			var fileNameWrapper = $('<span class="uploader__file-list__text">' + fileName + '</span>');

			state.listIndex++;

			var listItem = $('<li class="uploader__file-list__item" data-index="' + id + '"></li>');
			var removeLink = $('<span class="uploader__file-list__button"><button class="uploader__icon-button js-upload-remove-button glyphicon glyphicon-remove" data-index="' + id + '"></button></span>');

			if (options.fileTypeWhiteList.indexOf(getExtensionmdb(file.name).toLowerCase()) !== -1) {
				state.fileBatch.push({ file: file, id: id, fileName: fileName, fileSize: fileSize, lastdate: lastdate });
				sizeWrapper = $('<span class="uploader__file-list__size">' + formatBytesmdb(fileSize) + '</span>');
			} else {
				sizeWrapper = $('<span class="uploader__file-list__size"><span class="uploader__error">' + options.badFileTypeMessage + '</span></span>');
			}

			listItem
				.append(fileNameWrapper)
				.append(sizeWrapper)
				.append(removeLink);

			dommdb.fileList.append(listItem);
		}

		function uploadSubmitHandlermdb() {
			if (state.fileBatch.length !== 0) {
				var data = new FormData();
				for (var i = 0; i < state.fileBatch.length; i++) {
					data.append('files[]', state.fileBatch[i].file, state.fileBatch[i].fileName);
				}
				var d = new Date(state.fileBatch[0].lastdate);
				data.append("lastdate", d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate() + ' ' + d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds());
				data.append("userId", sessionStorage.getItem("userId"));
				$.ajax({
					type: 'POST',
					url: options.ajaxUrl,
					data: data,
					cache: false,
					contentType: false,
					processData: false,
					success: function (data) {
						var result = JSON.parse(data);
						if (result.code == 0) {
							swal("上传成功!");
							showFilemdb(false, 'fileDiv');
							getSearch();
						}
						else {
							swal("上传失败!");
						}
					},
					error: function (a, b, c) {
						swal("请求失败!");
					}
				});
			}
		}

		function selectFilesHandlermdb(e) {
			e.preventDefault();
			e.stopPropagation();
			if (!state.isUploading) {
				// files come from the input or a drop
				var files = e.target.files || e.dataTransfer.files || e.dataTransfer.getData;
				// process each incoming file
				for (var i = 0; i < files.length; i++) {
					addItemmdb(files[i]);
				}
			}
			renderControlsmdb();
		}

		function renderControlsmdb() {
			if (dommdb.fileList.children().size() !== 0) {
				dommdb.submitButton.removeClass('uploader__hide');
				dommdb.contentsContainer.addClass('uploader__hide');
			} else {
				dommdb.submitButton.addClass('uploader__hide');
				dommdb.contentsContainer.removeClass('uploader__hide');
			}
		}

		function removeItemHandlermdb(e) {
			e.preventDefault();
			swal({
				title: "确定删除吗?",
				showCancelButton: true,
				confirmButtonColor: "#DD6B55",
				confirmButtonText: "确定删除!",
				cancelButtonText: "取消删除!",
				closeOnConfirm: false,
				closeOnCancel: false
			},
				function (isConfirm) {
					if (isConfirm) {
						if (!state.isUploading) {
							var removeIndex = $(e.target).data('index');
							removeItemmdb(removeIndex);
							$(e.target).parent().remove();

							swal("删除成功!");
						}
						renderControlsmdb();
					} else {
						swal("取消成功!");
					}
				});
		}

		function getExtensionmdb(path) {
			var basename = path.split(/[\\/]/).pop();
			var pos = basename.lastIndexOf('.');

			if (basename === '' || pos < 1) {
				return '';
			}
			return basename.slice(pos + 1);
		}

		function formatBytesmdb(bytes, decimals) {
			if (bytes === 0) return '0 Bytes';
			var k = 1024;
			var dm = decimals + 1 || 3;
			var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
			var i = Math.floor(Math.log(bytes) / Math.log(k));
			return (bytes / Math.pow(k, i)).toPrecision(dm) + ' ' + sizes[i];
		}

		function cleanNamemdb(name) {
			name = name.replace(/\s+/gi, '-'); // Replace white space with dash
			return name.replace(/[^a-zA-Z0-9.\-]/gi, ''); // Strip any special characters
		}

		function removeItemmdb(id) {
			// remove from the batch
			for (var i = 0; i < state.fileBatch.length; i++) {
				if (state.fileBatch[i].id === parseInt(id)) {
					state.fileBatch.splice(i, 1);
					break;
				}
			}
			// remove from the DOM
			dommdb.fileList.find('li[data-index="' + id + '"]').remove();
		}