用Jquery plugin 实现---多文件上传

合集下载

用jQueryFileUpload做的上传控件demo,支持同页面多个上传按钮

用jQueryFileUpload做的上传控件demo,支持同页面多个上传按钮

⽤jQueryFileUpload做的上传控件demo,⽀持同页⾯多个上传按钮需求有这么⼀个需求,⼀个form有多个⽂件要上传,但⼜不是传统的图⽚批量上传那种,是类似下图这种需求,⼀开始是⽤的swfupload做的上传,但是问题是如果有多个按钮的话,就要写很多重复的代码,于为了代码的简洁所以就开始寻求其他的⽅法,期间试过uploadify,但是由于样式始终调不出来,最后就放弃了,直到发现这么个⼩巧的玩意,jQuery File Upload。

本⽂包含了upload的js实现,html的分析,css的实现等内容,⽂章末尾有git地址最简运⾏时官⽹下载的demo有N多js⽂件,⼀⼤堆js⽂件中只有⼏个才是必要的,其他的⽂件都是⼀些⽤不到的功能,只有在你需要的时候才需要引⽤。

<script src="/jquery/1.10.2/jquery.min.js" type="text/javascript"></script><script src="JS/jquery/jquery.iframe-transport.js"></script><script src="JS/jquery/jquery.ui.widget.js"></script><script src="JS/jquery/jquery.xdr-transport.js"></script><script src="JS/jquery/jquery.fileupload.js"></script>其中iframe那个⽂件是为了进⾏iframe上传,ui⽂件是能选完⽂件⾃动上传的必要⽂件,xdr那个是在ie下才需要的,最后⼀个⽂件是主体后台代码新建⼀个ashx的⽂件,这⾥建⽴⼀个uploadHandler.ashx,然后写⼊如下代码,⽤于保存。

jquery fileupload控件的用法

jquery fileupload控件的用法

jquery fileupload控件的用法`jQuery File Upload`是一个基于`jQuery`的文件上传插件,用于实现文件的异步上传功能。

其用法如下:1. 需要加载的`js`文件:`jquey-1.8.3.min.js`、`jquery-ui-widget.js`、`jquery.iframe-transport.js`、`jquery.fileupload.js`。

2. `html`代码:```html<input id="fileupload" type="file" name="files()" data-url="server/php/" multiple>```3. `js`代码:```javascript$(function () {$("#fileupload").fileupload({dataType: 'json',done: function (e, data) {$.each(data.result.files, function (index, file) {$("<p/>").text().appendTo(document.body);})},progressall: function (e, data) {var progress = parseInt(data.loaded / data.total * 100, 10);$("#progress .bar").css("width", progress + "%");},// 需要一个<div>容器用来显示进度<div id="progress"><div class="bar" style="width: 0%;"></div>});})```4. `API`:- `Initialization`:在上传按钮上调用`fileupload()`方法。

jquery插件ajaxupload实现文件上传操作

jquery插件ajaxupload实现文件上传操作

jquery插件ajaxupload实现⽂件上传操作本⽂实例讲述了jquery插件ajaxupload实现⽂件上传操作代码。

分享给⼤家供⼤家参考。

具体如下:运⾏效果截图如下:图1 ⽂件上传前图2 ⽂件上传后具体代码如下:1、创建页⾯并编写HTML上传⽂档:<div class="uploadFile"><span id="doc"><input type="text" disabled="disabled" /></span><input type="hidden" id="hidFileName" /><input type="button" id="btnUploadFile" value="上传" /><input type="button" id="btnDeleteFile" value="删除" /></div>上传图⽚:<div class="uploadImg"><img id="imgShow" src="/images/nophoto.gif" /><input type="hidden" id="hidImgName" /><input type="button" id="btnUploadImg" value="上传" /><input type="button" id="btnDeleteImg" value="删除" /></div>2、引⽤AjaxUpload.js⽂件<script src="/js/common/AjaxUpload.js" type="text/javascript"></script>3、编写JS脚本window.onload = function() {init(); //初始化}//初始化function init() {//初始化⽂档上传var btnFile = document.getElementById("btnUploadFile");var doc = document.getElementById("doc");var hidFileName = document.getElementById("hidFileName");document.getElementById("btnDeleteFile").onclick = function() { DelFile(doc, hidFileName); };g_AjxUploadFile(btnFile, doc, hidFileName);//初始化图⽚上传var btnImg = document.getElementById("btnUploadImg");var img = document.getElementById("imgShow");var hidImgName = document.getElementById("hidImgName");document.getElementById("btnDeleteImg").onclick = function() { DelImg(img, hidImgName); };g_AjxUploadImg(btnImg, img, hidImgName);}var g_AjxTempDir = "/file/temp/";//⽂档上传function g_AjxUploadFile(btn, doc, hidPut, action) {var button = btn, interval;new AjaxUpload(button, {action: ((action == null || action == undefined) ? '/Common/UploadHandler.ashx?fileType=file' : action),data: {},name: 'myfile',onSubmit: function(file, ext) {if (!(ext && /^(rar|zip|pdf|pdfx|txt|csv|xls|xlsx|doc|docx|RAR|ZIP|PDF|PDFX|TXT|CSV|XLS|XLSX|DOC|DOCX)$/.test(ext))) {alert("您上传的⽂档格式不对,请重新选择!");return false;}},onComplete: function(file, response) {flagValue = response;if (flagValue == "1") {alert("您上传的⽂档格式不对,请重新选择!");}else if (flagValue == "2") {alert("您上传的⽂档⼤于2M,请重新选择!");}else if (flagValue == "3") {alert("⽂档上传失败!");}else {hidPut.value = response;doc.innerHTML="<a href='" + g_AjxTempDir + response + "' target='_blank'>" + response + "</a>";}}});}//图⽚上传function g_AjxUploadImg(btn, img, hidPut) {var button = btn, interval;new AjaxUpload(button, {action: '/Common/UploadHandler.ashx?fileType=img',data: {},name: 'myfile',onSubmit: function(file, ext) {if (!(ext && /^(jpg|JPG|png|PNG|gif|GIF)$/.test(ext))) {alert("您上传的图⽚格式不对,请重新选择!");return false;}},onComplete: function(file, response) {flagValue = response;if (flagValue == "1") {alert("您上传的图⽚格式不对,请重新选择!");}else if (flagValue == "2") {alert("您上传的图⽚⼤于200K,请重新选择!");}else if (flagValue == "3") {alert("图⽚上传失败!");}else {img.src = g_AjxTempDir + response;}}});}//删除⽂档function DelFile(doc, hidPut) {hidPut.value = "";doc.innerHTML = "<input type=\"text\" disabled=\"disabled\" />";}//删除图⽚function DelImg(img, hidPut) {hidPut.value = "";img.src = "/images/nophoto.gif";}4、创建/Common/UploadHandler.ashx处理程序<%@ WebHandler Language="C#" Class="UploadHandler" %>using System;using System.Web;using System.Text.RegularExpressions;using System.IO;public class UploadHandler : IHttpHandler {private string _filedir = ""; //⽂件⽬录/// <summary>/// 处理上传⽂件(1:⽂件格式不正确、2:⽂件⼤⼩不正确、3:上传失败、⽂件名称:上传成功)/// </summary>/// <param name="context"></param>public void ProcessRequest (HttpContext context) {_filedir = context.Server.MapPath(@"/file/temp/");try{string result = "3";string fileType = context.Request.QueryString["fileType"]; //获取上传⽂件类型if (fileType == "file"){result = UploadFile(context); //⽂档上传}else if (fileType == "img"){result = UploadImg(context); //图⽚上传}context.Response.Write(result);}catch{context.Response.Write("3");//3⽂件上传失败}}/// <summary>/// ⽂档上传/// </summary>/// <param name="context"></param>/// <returns></returns>private string UploadFile(HttpContext context){int cout = context.Request.Files.Count;if (cout > 0){HttpPostedFile hpf = context.Request.Files[0];if (hpf != null){string fileExt = Path.GetExtension(hpf.FileName).ToLower();//只能上传⽂件,过滤不可上传的⽂件类型string fileFilt = ".rar|.zip|.pdf|.pdfx|.txt|.csv|.xls|.xlsx|.doc|.docx......";if (fileFilt.IndexOf(fileExt) <= -1){return "1";}//判断⽂件⼤⼩int length = hpf.ContentLength;if (length > 2097152){return "2";}Random rd = new Random();DateTime nowTime = DateTime.Now;string newFileName = nowTime.Year.ToString() + nowTime.Month.ToString() + nowTime.Day.ToString() + nowTime.Hour.ToString() + nowTime.Minute.ToString() + nowTime.Second.ToString() + rd.Next(1000, 1000000) + Path.GetExtension(hpf.FileName); if (!Directory.Exists(_filedir)){Directory.CreateDirectory(_filedir);}string fileName = _filedir + newFileName;hpf.SaveAs(fileName);return newFileName;}}return "3";}/// <summary>/// 图⽚上传/// </summary>/// <param name="context"></param>/// <returns></returns>private string UploadImg(HttpContext context){int cout = context.Request.Files.Count;if (cout > 0){HttpPostedFile hpf = context.Request.Files[0];if (hpf != null){string fileExt = Path.GetExtension(hpf.FileName).ToLower();//只能上传⽂件,过滤不可上传的⽂件类型string fileFilt = ".gif|.jpg|.php|.jsp|.jpeg|.png|......";if (fileFilt.IndexOf(fileExt) <= -1){return "1";}//判断⽂件⼤⼩}Random rd = new Random();DateTime nowTime = DateTime.Now;string newFileName = nowTime.Year.ToString() + nowTime.Month.ToString() + nowTime.Day.ToString() + nowTime.Hour.ToString() + nowTime.Minute.ToString() + nowTime.Second.ToString() + rd.Next(1000, 1000000) + Path.GetExtension(hpf.FileName); if (!Directory.Exists(_filedir)){Directory.CreateDirectory(_filedir);}string fileName = _filedir + newFileName;hpf.SaveAs(fileName);return newFileName;}}return "3";}#region IHttpHandler 成员public bool IsReusable{get { throw new NotImplementedException(); }}#endregion}附件1:页⾯CSS样式/*上传⽂件*/.uploadFile{margin-bottom:10px;}/*上传图⽚*/.uploadImg{}.uploadImg img{width:102px; height:64px; border:1px solid #CCCCCC; display: block;}附件2:AjaxUpload.js⽂件/*** AJAX Upload ( /ajax-upload/ )* Copyright (c) Andris Valums* Licensed under the MIT license ( /mit-license/ )* Thanks to Gary Haran, David Mark, Corey Burns and others for contributions*/(function () {/* global window *//* jslint browser: true, devel: true, undef: true, nomen: true, bitwise: true, regexp: true, newcap: true, immed: true *//*** Wrapper for FireBug's console.log*/function log() {if (typeof(console) != 'undefined' && typeof(console.log) == 'function') {Array.prototype.unshift.call(arguments, '[Ajax Upload]');console.log(Array.prototype.join.call(arguments, ' '));}}/*** Attaches event to a dom element.* @param {Element} el* @param type event name* @param fn callback This refers to the passed element*/function addEvent(el, type, fn) {if (el.addEventListener) {el.addEventListener(type, fn, false);} else if (el.attachEvent) {el.attachEvent('on' + type, function () {fn.call(el);});} else {throw new Error('not supported or DOM not loaded');}}/*** Attaches resize event to a window, limiting* number of event fired. Fires only when encounteres* delay of 100 after series of events.** Some browsers fire event multiple times when resizing* /dom/events/resize.html** @param fn callback This refers to the passed element*/function addResizeEvent(fn) {var timeout;addEvent(window, 'resize', function () {if (timeout) {clearTimeout(timeout);}timeout = setTimeout(fn, 100);});}// Needs more testing, will be rewriten for next version// getOffset function copied from jQuery lib (/)if (document.documentElement.getBoundingClientRect) {// Get Offset using getBoundingClientRect// /blog/getboundingclientrect-is-awesome/var getOffset = function (el) {var box = el.getBoundingClientRect();var doc = el.ownerDocument;var body = doc.body;var docElem = doc.documentElement; // for ievar clientTop = docElem.clientTop || body.clientTop || 0;var clientLeft = docElem.clientLeft || body.clientLeft || 0;// In Internet Explorer 7 getBoundingClientRect property is treated as physical,// while others are logical. Make all logical, like in IE8.var zoom = 1;if (body.getBoundingClientRect) {var bound = body.getBoundingClientRect();zoom = (bound.right - bound.left) / body.clientWidth;clientTop = 0;clientLeft = 0;}var top = box.top / zoom + (window.pageYOffset || docElem && docElem.scrollTop / zoom || body.scrollTop / zoom) - clientTop, left = box.left / zoom + (window.pageXOffset || docElem && docElem.scrollLeft / zoom || body.scrollLeft / zoom) - clientLeft; return {top: top,left: left};};} else {// Get offset adding all offsetsvar getOffset = function (el) {var top = 0,left = 0;do {top += el.offsetTop || 0;left += el.offsetLeft || 0;el = el.offsetParent;} while (el);return {left: left,top: top};};}/*** Returns left, top, right and bottom properties describing the border-box,* in pixels, with the top-left relative to the body* @param {Element} el* @return {Object} Contains left, top, right,bottom*/function getBox(el) {var left, right, top, bottom;var offset = getOffset(el);left = offset.left;top = offset.top;right = left + el.offsetWidth;bottom = top + el.offsetHeight;return {left: left,right: right,top: top,bottom: bottom};}/*** Helper that takes object literal* and add all properties to element.style* @param {Element} el* @param {Object} styles*/function addStyles(el, styles) {for (var name in styles) {if (styles.hasOwnProperty(name)) {el.style[name] = styles[name];}}}/*** Function places an absolutely positioned* element on top of the specified element* copying position and dimentions.* @param {Element} from* @param {Element} to*/function copyLayout(from, to) {var box = getBox(from);addStyles(to, {position: 'absolute',left: box.left + 'px',top: box.top + 'px',width: from.offsetWidth + 'px',height: from.offsetHeight + 'px'});}/*** Creates and returns element from html chunk* Uses innerHTML to create an element*/var toElement = (function () {var div = document.createElement('div');return function (html) {div.innerHTML = html;var el = div.firstChild;return div.removeChild(el);};})();/*** Function generates unique id* @return unique id*/var getUID = (function () {var id = 0;return function () {return 'ValumsAjaxUpload' + id++;};})();/*** Get file name from path* @param {String} file path to file* @return filename*/function fileFromPath(file) {/*** Get file extension lowercase* @param {String} file name* @return file extenstion*/function getExt(file) {return (-1 !== file.indexOf('.')) ? file.replace(/.*[.]/, '') : '';}function hasClass(el, name) {var re = new RegExp('\\b' + name + '\\b');return re.test(el.className);}function addClass(el, name) {if (!hasClass(el, name)) {el.className += ' ' + name;}}function removeClass(el, name) {var re = new RegExp('\\b' + name + '\\b');el.className = el.className.replace(re, '');}function removeNode(el) {el.parentNode.removeChild(el);}/*** Easy styling and uploading* @constructor* @param button An element you want convert to* upload button. Tested dimentions up to 500x500px* @param {Object} options See defaults below.*/window.AjaxUpload = function (button, options) {this._settings = {// Location of the server-side upload scriptaction: 'upload.php',// File upload namename: 'userfile',// Additional data to senddata: {},// Submit file as soon as it's selectedautoSubmit: true,// The type of data that you're expecting back from the server.// html and xml are detected automatically.// Only useful when you are using json data as a response.// Set to "json" in that case.responseType: false,// Class applied to button when mouse is hoveredhoverClass: 'hover',// Class applied to button when AU is disableddisabledClass: 'disabled',// When user selects a file, useful with autoSubmit disabled// You can return false to cancel uploadonChange: function (file, extension) {},// Callback to fire before file is uploaded// You can return false to cancel uploadonSubmit: function (file, extension) {},// Fired when file upload is completed// WARNING! DO NOT USE "FALSE" STRING AS A RESPONSE!onComplete: function (file, response) {}};// Merge the users options with our defaultsfor (var i in options) {if (options.hasOwnProperty(i)) {this._settings[i] = options[i];}}// button isn't necessary a dom elementif (button.jquery) {// jQuery object was passedbutton = button[0];} else if (typeof button == "string") {if (/^#.*/.test(button)) {// If jQuery user passes #elementId don't break itbutton = button.slice(1);}button = document.getElementById(button);}if (!button || button.nodeType !== 1) {throw new Error("Please make sure that you're passing a valid element"); }if (button.nodeName.toUpperCase() == 'A') {// disable linkaddEvent(button, 'click', function (e) {if (e && e.preventDefault) {e.preventDefault();} else if (window.event) {window.event.returnValue = false;}});}// DOM elementthis._button = button;// DOM elementthis._input = null;// If disabled clicking on button won't do anythingthis._disabled = false;// if the button was disabled before refresh if will remain// disabled in FireFox, let's fix itthis.enable();this._rerouteClicks();};// assigning methods to our classAjaxUpload.prototype = {setData: function (data) {this._settings.data = data;disable: function () {addClass(this._button, this._settings.disabledClass);this._disabled = true;var nodeName = this._button.nodeName.toUpperCase();if (nodeName == 'INPUT' || nodeName == 'BUTTON') {this._button.setAttribute('disabled', 'disabled');}// hide inputif (this._input) {// We use visibility instead of display to fix problem with Safari 4 // The problem is that the value of input doesn't change if it// has display none when user selects a filethis._input.parentNode.style.visibility = 'hidden';}},enable: function () {removeClass(this._button, this._settings.disabledClass);this._button.removeAttribute('disabled');this._disabled = false;},/*** Creates invisible file input* that will hover above the button* <div><input type='file' /></div>*/_createInput: function () {var self = this;var input = document.createElement("input");input.setAttribute('type', 'file');input.setAttribute('name', this._);addStyles(input, {'position': 'absolute',// in Opera only 'browse' button// is clickable and it is located at// the right side of the input'right': 0,'margin': 0,'padding': 0,'fontSize': '480px','cursor': 'pointer'});var div = document.createElement("div");addStyles(div, {'display': 'block','position': 'absolute','overflow': 'hidden','margin': 0,'padding': 0,'opacity': 0,// Make sure browse button is in the right side// in Internet Explorer'direction': 'ltr',//Max zIndex supported by Opera 9.0-9.2'zIndex': 2147483583});// Make sure that element opacity exists.// Otherwise use IE filterif (div.style.opacity !== "0") {if (typeof(div.filters) == 'undefined') {throw new Error('Opacity not supported by the browser');}div.style.filter = "alpha(opacity=0)";}addEvent(input, 'change', function () {if (!input || input.value === '') {return;}// Get filename from input, required// as some browsers have path instead of itvar file = fileFromPath(input.value);if (false === self._settings.onChange.call(self, file, getExt(file))) { self._clearInput();return;}// Submit form when value is changedif (self._settings.autoSubmit) {self.submit();}});addEvent(input, 'mouseover', function () {addClass(self._button, self._settings.hoverClass);});addEvent(input, 'mouseout', function () {removeClass(self._button, self._settings.hoverClass);// We use visibility instead of display to fix problem with Safari 4 // The problem is that the value of input doesn't change if it// has display none when user selects a fileinput.parentNode.style.visibility = 'hidden';});div.appendChild(input);document.body.appendChild(div);this._input = input;},_clearInput: function () {if (!this._input) {return;}// this._input.value = ''; Doesn't work in IE6removeNode(this._input.parentNode);this._input = null;this._createInput();removeClass(this._button, this._settings.hoverClass);/*** Function makes sure that when user clicks upload button,* the this._input is clicked instead*/_rerouteClicks: function () {var self = this;// IE will later display 'access denied' error// if you use using self._input.click()// other browsers just ignore click()addEvent(self._button, 'mouseover', function () {if (self._disabled) {return;}if (!self._input) {self._createInput();}var div = self._input.parentNode;copyLayout(self._button, div);div.style.visibility = 'visible';});// commented because we now hide input on mouseleave/*** When the window is resized the elements* can be misaligned if button position depends* on window size*///addResizeEvent(function(){// if (self._input){// copyLayout(self._button, self._input.parentNode);// }//});},/*** Creates iframe with unique name* @return {Element} iframe*/_createIframe: function () {// We can't use getTime, because it sometimes return// same value in safari :(var id = getUID();// We can't use following code as the name attribute// won't be properly registered in IE6, and new window// on form submit will open// var iframe = document.createElement('iframe');// iframe.setAttribute('name', id);var iframe = toElement('<iframe src="javascript:false;" name="' + id + '" />');// src="javascript:false; was added// because it possibly removes ie6 prompt// "This page contains both secure and nonsecure items"// Anyway, it doesn't do any harm.iframe.setAttribute('id', id);iframe.style.display = 'none';document.body.appendChild(iframe);return iframe;},/*** Creates form, that will be submitted to iframe* @param {Element} iframe Where to submit* @return {Element} form*/_createForm: function (iframe) {var settings = this._settings;// We can't use the following code in IE6// var form = document.createElement('form');// form.setAttribute('method', 'post');// form.setAttribute('enctype', 'multipart/form-data');// Because in this case file won't be attached to requestvar form = toElement('<form method="post" enctype="multipart/form-data"></form>'); form.setAttribute('action', settings.action);form.setAttribute('target', );form.style.display = 'none';document.body.appendChild(form);// Create hidden input element for each data keyfor (var prop in settings.data) {if (settings.data.hasOwnProperty(prop)) {var el = document.createElement("input");el.setAttribute('type', 'hidden');el.setAttribute('name', prop);el.setAttribute('value', settings.data[prop]);form.appendChild(el);}}return form;},/*** Gets response from iframe and fires onComplete event when ready* @param iframe* @param file Filename to use in onComplete callback*/_getResponse: function (iframe, file) {// getting responsevar toDeleteFlag = false,self = this,settings = this._settings;addEvent(iframe, 'load', function () {if ( // For Safariiframe.src == "javascript:'%3Chtml%3E%3C/html%3E';" ||// For FF, IEiframe.src == "javascript:'<html></html>';") {// First time around, do not delete.// We reload to blank page, so that reloading main page// does not re-submit the post.if (toDeleteFlag) {// Fix busy state in FF3removeNode(iframe);},0);}return;}var doc = iframe.contentDocument ? iframe.contentDocument : window.frames[iframe.id].document; // fixing Opera 9.26,10.00if (doc.readyState && doc.readyState != 'complete') {// Opera fires load event multiple times// Even when the DOM is not ready yet// this fix should not affect other browsersreturn;}// fixing Opera 9.64if (doc.body && doc.body.innerHTML == "false") {// In Opera 9.64 event was fired second time// when body.innerHTML changed from false// to server response approx. after 1 secreturn;}var response;if (doc.XMLDocument) {// response is a xml document Internet Explorer propertyresponse = doc.XMLDocument;} else if (doc.body) {// response is html document or plain textresponse = doc.body.innerHTML;if (settings.responseType && settings.responseType.toLowerCase() == 'json') {// If the document was sent as 'application/javascript' or// 'text/javascript', then the browser wraps the text in a <pre>// tag and performs html encoding on the contents. In this case,// we need to pull the original text content from the text node's// nodeValue property to retrieve the unmangled content.// Note that IE6 only understands text/htmlif (doc.body.firstChild && doc.body.firstChild.nodeName.toUpperCase() == 'PRE') {response = doc.body.firstChild.firstChild.nodeValue;}if (response) {response = eval("(" + response + ")");} else {response = {};}}} else {// response is a xml documentresponse = doc;}settings.onComplete.call(self, file, response);// Reload blank page, so that reloading main page// does not re-submit the post. Also, remember to// delete the frametoDeleteFlag = true;// Fix IE mixed content issueiframe.src = "javascript:'<html></html>';";});},/*** Upload file contained in this._input*/submit: function () {var self = this,settings = this._settings;if (!this._input || this._input.value === '') {return;}var file = fileFromPath(this._input.value);// user returned false to cancel uploadif (false === settings.onSubmit.call(this, file, getExt(file))) {this._clearInput();return;}// sending requestvar iframe = this._createIframe();var form = this._createForm(iframe);// assuming following structure// div -> input type='file'removeNode(this._input.parentNode);removeClass(self._button, self._settings.hoverClass);form.appendChild(this._input);form.submit();// request set, clean upremoveNode(form);form = null;removeNode(this._input);this._input = null;// Get response from iframe and fire onComplete event when readythis._getResponse(iframe, file);// get ready for next requestthis._createInput();}};})();更多精彩内容请参考专题,和进⾏学习。

聊一聊jquery文件上传(支持多文件上传)

聊一聊jquery文件上传(支持多文件上传)

聊⼀聊jquery⽂件上传(⽀持多⽂件上传)谈到⽂件上传,现在⼀般都⽤现成的组件可以使⽤。

PC端的可以使⽤uploadify。

针对微⽹站H5也有uploadifive。

但是这组件并不能满⾜各种场景的需求,例如:预览 切图 放⼤缩⼩,取消之类的。

普通上传HTML:<form action="Upload"method="post" enctype="multipart/form-data"><input id="File1"name="fileupload" type="file" value="" /><input id="" type="submit" value="上传" /></form>服务端:[HttpPost]public JsonResult Upload(){if (Request.Files.Count > 0){if (Request.Files.Count == 1){HttpPostedFileBase file = Request.Files[0];if (file.ContentLength > 0){string title = string.Empty;title = DateTime.Now.ToString("yyyyMMddHHmmss") + "_" + Path.GetFileName(file.FileName);string path = "../UploadFile/" + title;path = System.Web.HttpContext.Current.Server.MapPath(path);file.SaveAs(path);return Json(new { status = true, url = path });}}else{string[] urllist = new string[Request.Files.Count];for (int i = 0; i < Request.Files.Count; i++){HttpPostedFileBase file = Request.Files[i];if (file.ContentLength > 0){string title = string.Empty;title = DateTime.Now.ToString("yyyyMMddHHmmss") + "_" + Path.GetFileName(file.FileName);string path = "../UploadFile/" + title;path = System.Web.HttpContext.Current.Server.MapPath(path);file.SaveAs(path);urllist[i] = path;}}return Json(new { status = true, url = urllist });}}else{return Json(new { status = false, url = "",msg="没有⽂件" });}return Json(new { status = false, url = "",msg=""});}后端代码没什么不同的,⼀直就是如此主要是前端html,我标记为红⾊字体的属性⼀个都不能少,少⼀个都不可能完成上传action作⽤:该属性的值指向要提交到某⼀个页⾯,缺少它会不知道提交给谁可以提交的页⾯:abc.aspx abc.ashx mvc的控制器⽅法 webapi接⼝以及其他后端处理程序method作⽤:该属性的值决定以何种⽅式提交,缺少它会报404可以取的值:post get put deleteenctype作⽤:指定类型缺少它在后台接收时⽂件并不会包含进去可以取的值:multipart/form-data application/x-www-form-urlencoded text/plain 此处必须使⽤ multipart/form-data才能将⽂件传到服务端nameinput file ⾥⾯必须包含name属性才能够将⽂件传递到服务器,具体原因不知道,有兴趣的可以尝试下如果有知道的⿇烦解惑相信到了这⾥你⼀定可以完成上传⽂件操作了!⽂件类型筛选能完成基本的⽂件上传操作之后,我们会对它有更多的要求,⽐如:⽂件筛选相信⼤家都不愿意让⼈什么类型的⽂件都往服务器上传,万⼀是病毒或者脚本之类的就⿇烦⼤了。

jQuery上传文件的方法

jQuery上传文件的方法

jQuery上传⽂件的⽅法<div id="login-form"><!--<form id="uploadSongsForm" method="POST" action="/upload" enctype="multipart/form-data">--><form id="uploadSongsForm" enctype="multipart/form-data"><div id="showMp3Files" class="tittle"><div class=" form-group"><input type="file" name="file" id="mp3Files"></div><div class=" form-group"><button type="reset" id="clearmp3" class="btn btn-dark">清除选择歌曲</button></div><div class=" form-group"><input type="submit" value="上传" id="uploadBtn" class=" btn btn-primary"></div></div></form>jq代码$("#uploadSongsForm").submit(function () {$.post("/upload",{file:file},function (info) {if(info.flag){alert(info.msg)}else{//添加失败alert(info.msg);}});return false;});controller代码private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(FileUploadController.class);@GetMapping("/upload")public String upload() {return "upload";}@PostMapping("/upload")@ResponseBodypublic ResultInfo upload(@RequestParam("file") MultipartFile file) {ResultInfo info=new ResultInfo();info.setFlag(false);if (file.isEmpty()) {info.setMsg("⽂件为空");info.setFlag(false);return info;}String fileName = file.getOriginalFilename();String filePath = "/mp3/";System.out.println("⽂件名:"+fileName);File dest = new File(filePath + fileName);try {file.transferTo(dest);("succeed");info.setFlag(true);info.setMsg("上传成功");return info;} catch (IOException e) {LOGGER.error(e.toString(), e);}info.setMsg("上传失败");return info;}就我的猜测是jq段肯定是有错误的。

jquery.multifile多文件上传

jquery.multifile多文件上传

Jquery使用插件实现多文件同时上传的功能需要用到的相关jar包和第三方插件分别为:jquery-1.4.2.min.js,jquery.MultiFile.js,commons-io-1.4.jar,commons-fi leupload-1.2.1.jar引入相关的js和jar文件即可开始上传的操作://此处的上传没有判断文件上传的类型,因为使用了jquery的插件,所以此处的上传类型在前台的页面做控制final long MAX_SIZE = 3 * 1024 * 1024;// 设置上传文件最大为 3M response.setContentType("text/html");// 设置字符编码为UTF-8, 这样支持汉字显示response.setCharacterEncoding("GBK");// 实例化一个硬盘文件工厂,用来配置上传组件ServletFileUpload DiskFileItemFactory dfif = new DiskFileItemFactory();dfif.setSizeThreshold(4096);// 设置上传文件时用于临时存放文件的内存大小,这里是4K.多于的部分将临时存在硬盘dfif.setRepository(new File("c:\\"));// 设置存放临时文件的目录,web根目录下的ImagesUploadTemp目录// 用以上工厂实例化上传组件ServletFileUpload sfu = new ServletFileUpload(dfif);// 设置最大上传尺寸sfu.setSizeMax(MAX_SIZE);// 从request得到所有上传域的列表List fileList = null;try {fileList = sfu.parseRequest(request);} catch (FileUploadException e) {// 处理文件尺寸过大异常if (e instanceof SizeLimitExceededException) {out.println("文件尺寸超过规定大小:" + MAX_SIZE + "字节<p />"); out.println("<a href=\"upload.html\" target=\"_top\">返回</a>"); return;}e.printStackTrace();}// 没有文件上传if (fileList == null || fileList.size() == 0) {out.println("请选择上传文件<p />");out.println("<a href=\"upload_sence.jsp\" target=\"_top\">返回</a>");return;}// 得到所有上传的文件Iterator fileItr = fileList.iterator();// 循环处理所有文件while (fileItr.hasNext()) {FileItem fileItem = null;String fpath = "";long size = 0;// 得到当前文件fileItem = (FileItem) fileItr.next();if (fileItem.isFormField()) {//如果不是上传域,而是普通的表单域(如:<input type="text|radio">)则在此进行处理}// 忽略简单form字段而不是上传域的文件域(<input type="text" />等) if (fileItem == null || fileItem.isFormField()) {continue;}// 得到文件的完整路径fpath = fileItem.getName();// 得到文件的大小size = fileItem.getSize();if ("".equals(fpath) || size == 0) {out.println("请选择上传文件<p />");out.println("<a href=\"upload_sence.jsp\" target=\"_top\">返回</a>");return;}// 得到去除路径的文件名String t_name = fpath.substring(stIndexOf("\\") + 1);// 得到文件的扩展名(无扩展名时将得到全名)String t_ext = t_name.substring(t_stIndexOf(".") + 1);// 根据系统时间生成上传后保存的文件名//String prefix = String.valueOf(now);// 保存的最终文件完整路径,保存在web根目录下的ImagesUploaded目录下String u_name = request.getRealPath("/") + "uploaded\\" + t_name + "." + t_ext;File file = new File(u_name);fileItem.write(file);out.println("文件上传成功. 已保存为: " + t_name + "." + t_ext+ " &nbsp;&nbsp;文件大小: " + size + "字节<p />");out.println("<a href=\"upload_sence.jsp\" target=\"_top\">继续上传</a>");}PS:如果你上传文件时需要使用当前时间的毫秒数来做上传文件的文件名,那么请不要使用此种方式上传,因为该方式可以让用户通过一个文本域同时上传多个文件,而多个文件是同时进行上传操作的,所以在同一时间内最后一个上传的文件很可能会将前边的文件覆盖掉,造成文件的丢失相应的上传页面代码如下:<%@ page language="java" contentType="text/html; charset=GBK"pageEncoding="GBK"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=GBK"><title>JQeury多文件上传测试</title><!--引入jquery的主文件和上传的插件,注意下方蓝色文件显示的地方,只有使用了jquery相关插件的时候才可以这样写,其中class="multi"指定了该域可以使用jquery插件特有的属性,accept="gif|jpg"表示允许的上传文件类型,多个类型之间用|进行分割。

jQuery多图上传插件imgUp.js

jQuery多图上传插件imgUp.js

本文由我司收集整编,推荐下载,如有疑问,请与我司联系jQuery 多图上传插件imgUp.js2017/08/07 0 开发环境:idea mysql效果:前台步骤如下:1)首先导入imgPlugin.js注:实际项目中使用的时候只需要引用:imgPlugin.js 这个就可以了,因为这个是对imgUp.js 的封装script type= text/javascript src= ../style-wechat/js/imgPlugin.js /script2)在页面中加入它需要的jsscript type= text/javascript var imgUrls= ; $( #file ).takungaeImgup({ formData: { name : file }, url: 192.168.1.109:8080/imgUp , success: function(data) { imgUrls =data.url , ; }, error: function(err) { alert(err); } }); function addComm(){ jQuery.ajax({ url: /addComment.action , type: ‘POST’,data: {‘imageUrls’:imgUrls}, dataType: ‘json’, success: function (data) { alert( 发布成功); } }) } /script 3)在页面中代码添加内容div > section > div > section > img src= ../../style- wechat/images/a11.png > input type= file name= file id= file > /section /div /section /div aside > div > p > p > /div /aside 后台接受图片代码:tips:感谢大家的阅读,本文由我司收集整编。

jQuery插件实现文件上传功能(支持拖拽)

jQuery插件实现文件上传功能(支持拖拽)

jQuery插件实现⽂件上传功能(⽀持拖拽)先贴上源代码地址,。

然后直接进⼊主题啦,当然,如果你觉得我有哪⾥写的不对或者⽋妥的地⽅,欢迎留⾔指出。

在附上⼀些代码之前,我们还是先来了解下,上传⽂件的时候需要利⽤的⼀些必要的知识。

⾸先我们要说的就是FileReader对象,这是⼀个HTML5提出的,专门⽤来异步的读取⽤户计算机上⽂件的对象,。

所以如果我们想要使⽤它,那么⾸先我们得先创建⼀个FileReader对象。

var fr = new FileReader()1、这个对象拥有五个⽅法:下⾯附上⼀个例⼦:<input type="file" id="file"/><img src="" alt="" id="img"><script src="jquery.min.js"></script><script>var ipt = $('#file'),img = $('#img');ipt.change(function () {var fr = new FileReader();fr.readAsDataURL(this.files[0]);fr.onload = function () {img.attr('src', fr.result);}})</script>效果图:其他的⼏个⽅法也基本上⼤同⼩异,所以在这⾥就不做过多解释了。

2、这个对象还拥有三个状态常量:3、这个对象还拥有三个属性:4、6个事件处理程序:这⾥我们再来说说formData对象,同样的我们利⽤它来上传⽂件,⾸先需要创建⼀个formData对象实例var formData = new FormData(); 这个对象有⼀个append⽅法,该⽅法接受三个参数:name、value、filename在使⽤这个对象上传⽂件的时候,我们需要注意⼀点,需要在form标签上添加上enctype="multipart/form-data"这个属性,⽤来设置表单的MIME编码,因为默认的编码格式是application /x-www-form-urlencoded,不能⽤于⽂件上传,也可以在使⽤jQuery的$.ajax⽅法的时候,设置data属性为formData。

JQuery与springmvc实现多个文件上传操作

JQuery与springmvc实现多个文件上传操作

本文由我司收集整编,推荐下载,如有疑问,请与我司联系JQuery 与springmvc 实现多个文件上传操作1. 导入JQuery 相关JS 文件script src=“ @full_path path=“js/jquery.js”/“type=“text/javascript” /scriptscript src=“ @full_path path=“js/ajaxfileupload.js”/“type=“text/javascript” /script这边ajaxfileupload.js 有点特殊,请使用如下改造后的原文件内容:jQuery.extend({ var frameId = ‘jUploadFrame’ + id; var iframeHtml = ‘ iframe id=“‘ + frameId + ‘“name=“‘+ frameId + ‘“‘;if(window.ActiveXObject) if(typeof uri==‘boolean’){iframeHtml += ‘src=“‘+ ‘javascript:false’+ ‘“‘;else if(typeof uri==‘string’){iframeHtml += ‘src=“‘+ uri + ‘“‘;iframeHtml += ‘/ jQuery(iframeHtml).appendTo(document.body); return jQuery(‘#’+ frameId).get(0); createUploadForm: function(id, fileElementId, data) //create form var formId = ‘jUploadForm’+ id; var fileId = ‘jUploadFile’+ id; var form = jQuery(‘form action=““method=“POST”name=“‘+ formId + ‘“id=“‘+ formId + ‘“enctype=“multipart/form-data” /form if (data) { for ( var i in data) { jQuery( ‘ input type=“hidden”name=“‘ + i + ‘“value=“‘+ data[i] + ‘“ / ‘).appendTo(form);for (var i= 0; i fileElementId.length; i ++) { var oldElement = jQuery(‘#’+ fileElementId[i]); var newElement = jQuery(oldElement).clone(); jQuery(oldElement).attr(‘id’, fileElementId[i]); jQuery(oldElement).attr(‘name’,fileElementId[i]); jQuery(oldElement).before(newElement); jQuery(oldElement).appendTo(form); //set attributes jQuery(form).css(‘position’,‘absolute’);jQuery(form).css(‘top’,‘-1200px’); jQuery(form).css(‘left’,‘-1200px’);jQuery(form).appendTo(‘body’);return form; ajaxFileUpload: function(s) { // TODO introduce global settings, allowing the client to modify them for all requests, not only timeout s = jQuery.extend({}, jQuery.ajaxSettings, s); var id = new Date().getTime() var form = jQuery.createUploadForm(id, s.fileElementId, (typeof(s.data)==‘undefined’?false:s.data));。

JQuery批量上传插件Uploadify使用详解及参数说明

JQuery批量上传插件Uploadify使用详解及参数说明

JQuery批量上传插件Uploadify使用详解及参数说明Uploadify是JQuery的一个上传插件,实现的效果非常不错,带进度显示。

官方提供的实例是php版本的,您可以点击下面的链接进行浏览或下载。

∙官方下载∙官方文档∙官方演示效果图:部署和代码介绍:JSP前台页面:<script type="text/javascript">$(document).ready( function() {$("#uploadify").uploadify( {//初始化函数'uploader' :'uploadify.swf',//flash文件位置,注意路径'script' :'servlet/Upload',//后台处理的请求'cancelImg' :'images/cancel.png',//取消按钮图片'folder' :'uploads',//您想将文件保存到的路径'queueID' :'fileQueue',//与下面的上传文件列表id对应'queueSizeLimit' :8,//上传文件的数量'scriptData':{'a':'value1','b':'value2'},//向后台传的数据'fileDesc' :'rar文件或zip文件',//上传文件类型说明'fileExt' :'*.rar;*.zip', //控制可上传文件的扩展名,启用本项时需同时声明fileDesc'method':'get',//如果向后台传输数据,必须是get'sizeLimit':1000,//文件上传的大小限制,单位是字节'auto' :false,//是否自动上传'multi' :true,'simUploadLimit' :2,//同时上传文件的数量'buttonText' :'BROWSE',//浏览按钮图片'onComplete': function(event, queueID, fileObj,serverData,data) {//当上传完成后的回调函数,ajax方式哦~~alert(data.speed);}});});</script><script type="text/javascript"src="js/jquery-1.3.2.min.js"></script><script type="text/javascript"src="js/swfobject.js"></script><script type="text/javascript"src="js/jquery.uploadify.v2.1.0.min.js"></script><div id="fileQueue"></div><input type="file"name="uploadify"id="uploadify"/><p><a href="javascript:jQuery('#uploadify').uploadifyUpload()">开始上传</a>&nbsp; <a href="javascript:jQuery('#uploadify').uploadifyClearQueue()">取消所有上传</a> </p>java后台:String savePath = this.getServletConfig().getServletContext().getRealPath("");savePath = savePath + "/uploads/";File f1 = new File(savePath);System.out.println(savePath);if (!f1.exists()) {f1.mkdirs();}DiskFileItemFactory fac = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(fac); upload.setHeaderEncoding("utf-8");List fileList = null;try {fileList = upload.parseRequest(request);} catch (FileUploadException ex) {ex.printStackTrace();return;}Iterator it = fileList.iterator();while (it.hasNext()) {FileItem item = (FileItem) it.next();if (!item.isFormField()) {name = item.getName();long size = item.getSize();String type = item.getContentType();if (name == null || name.trim().equals("")) { continue;}// 扩展名格式:if (stIndexOf(".") >= 0) {extName = name.substring(stIndexOf("."));}File file = null;do {// 生成文件名:name = UUID.randomUUID().toString();file = new File(savePath + name + extName);} while (file.exists());File saveFile = new File(savePath + name + extName);try {item.write(saveFile);} catch (Exception e) {e.printStackTrace();}}}response.getWriter().print(name + extName);代码很好懂,不讲解了。

blueimp jquery-file-upload 事例

blueimp jquery-file-upload 事例

blueimp jquery-file-upload 事例Blueimp jQuery-File-Upload示例前言:Blueimp jQuery-File-Upload是一款强大的文件上传插件,通过它,我们可以方便地在网页中实现文件上传功能。

本文将介绍一些实际应用中的Blueimp jQuery-File-Upload事例,展示其使用方法和效果。

一、注册和上传文件在使用Blueimp jQuery-File-Upload之前,我们首先需要在网页中引入该插件的相关文件。

一般来说,我们需要引入jQuery库、必要的CSS样式和脚本文件。

接着,在网页中创建一个容器,用于显示上传文件的进度和结果。

然后,我们需要给该容器绑定一个点击事件,当用户点击该容器时,会触发文件选择框,用户可以选择本地的文件进行上传。

二、添加文件队列和文件预览在文件选择完成后,Blueimp jQuery-File-Upload会自动将选择的文件添加到上传队列中,并在页面上展示文件的预览效果。

我们可以通过修改相关配置来自定义文件队列的展示样式,如设置默认的缩略图、添加删除按钮等。

通过这样的操作,用户可以清晰地看到自己选择的文件是否正确,提高了用户的操作体验。

三、指定上传目标和执行上传接下来,我们需要指定文件上传的目标路径或后台处理文件的URL 地址,并且处理上传按钮的点击事件。

当用户点击上传按钮时,Blueimp jQuery-File-Upload会自动将文件上传至指定的目标,并在页面上实时显示上传进度。

此时,我们可以通过监听相关的事件来获取上传进度,如上传开始前、进度更新和上传成功等。

四、处理上传结果在文件上传完成后,我们可以获取上传成功的文件信息,并可以对上传结果进行一些后续处理。

比如,可以将上传成功的文件信息保存到数据库中,方便以后的查阅或操作。

此外,我们也可以自定义上传失败的处理方式,如提示用户重新上传或显示上传错误信息等。

几种js实现的动态多文件上传

几种js实现的动态多文件上传

方式一:事先写好多个input.在点击时才显示。

也就是说上传的最大个数是写死了的。

html<p><a href='#' onclick='javascript:viewnone(more1)'>添加附件</a><div id='more1' style='display:none'><input type="file" name="attach1" size="50"javascript:viewnone(more2)></span></div><div id='more2' style='display:none'><input type="file" name="attach2" size="50"'></div></p>js<SCRIPT language="javascript">function viewnone(e){e.style.display=(e.style.display=="none")?"":"none";}</script>方式二:这种方式的动态多文件上传是实现了的,很简单的,不说废话看codehtml<input type="button" name="button" value="添加附件" onclick="addInput()"><input type="button" name="button" value="删除附件" onclick="deleteInput()"><span id="upload"></span>js<script type="text/javascript">var attachname = "attach";var i=1;function addInput(){if(i>0){var attach = attachname + i ;if(createInput(attach))i=i+1;}}function deleteInput(){if(i>1){i=i-1;if(!removeInput())i=i+1;}}function createInput(nm){var aElement=document.createElement("input");=nm;aElement.id=nm;aElement.type="file";aElement.size="50";//aElement.value="thanks";//aElement.onclick=Function("asdf()");if(document.getElementById("upload").appendChild(aEle ment) == null)return false;return true;}function removeInput(nm){var aElement = document.getElementById("upload");if(aElement.removeChild(stChild) == null)return false;return true;}</script>方式三:动态多文件上传,只是在oFileInput.click();这个地方,这样做就不能上传这个文件了,因为发现它在上传之时就把这个input中的文件置空了。

jQuery实现异步上传一个或多个文件

jQuery实现异步上传一个或多个文件

jQuery实现异步上传⼀个或多个⽂件本⽂实例为⼤家分享了jQuery实现异步上传⼀个或多个⽂件的具体代码,供⼤家参考,具体内容如下⾸先使⽤SpringMvc⽂件上传,需要引⼊第三⽅上传⽂件的jar:<dependency><groupId>commons-fileupload</groupId><artifactId>commons-fileupload</artifactId><version>1.3.1</version></dependency><dependency><groupId>commons-io</groupId><artifactId>commons-io</artifactId><version>2.4</version></dependency>响应json需要导⼊的包:<dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.9.0</version></dependency><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-core</artifactId><version>2.9.0</version></dependency><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-annotations</artifactId><version>2.9.0</version></dependency>接下来看jsp⽂件:<%@ page contentType="text/html;charset=UTF-8" language="java" %><html><head><title>⾸页</title></head><body><p>同步上传⼀个⽂件</p><form action="upload/testUpload" method="post" enctype="multipart/form-data"><input type="file" name="upload"><br><input type="submit" value="上传"></form><hr><p>异步上传⼀个⽂件</p><form id="formData" method="post" enctype="multipart/form-data"><input type="file" name="upload"><br><input id="sub" type="button" value="上传"></form><hr><p>异步上传⼀个⽂件,且表单有其他数据</p><form id="formData2" method="post" enctype="multipart/form-data">编&emsp;号:<input type="text" name="id"><br>账户名:<input type="text" name="name"><br>⾦&emsp;额:<input type="text" name="money"><br><input type="file" name="upload"><br><input id="sub2" type="button" value="上传"></form><hr><p>异步上传多个⽂件,且表单有其他数据</p><form id="formData3" method="post" enctype="multipart/form-data">编&emsp;号:<input type="text" name="id"><br>账户名:<input type="text" name="name"><br>⾦&emsp;额:<input type="text" name="money"><br><input type="file" name="upload" multiple="multiple"><br><input id="sub3" type="button" value="上传"></form><script type="text/javascript" src="js/jquery-3.3.1.js"></script><script>$(function () {//异步上传⼀个⽂件$("#sub").click(function () {var file = new FormData($("#formData")[0]);$.post({url:'upload/testUpload',contentType:false, //jQuery不要去设置Content-Type请求头processData:false, //jQuery不要去处理发送的数据cache:false, //不缓存dataType:'json', //返回类型jsondata:file, //⽂件数据success:function (res) {console.log(res);}});});//异步上传⼀个⽂件,带表单参数$("#sub2").click(function () {//将form表单转换为FormData对象var data = new FormData(document.querySelector("#formData2")); $.post({url:'upload/testUpload2',contentType:false, //jQuery不要去设置Content-Type请求头processData:false, //jQuery不要去处理发送的数据cache:false, //不缓存dataType:'json', //返回类型jsondata:data, //表单数据success:function (res) {console.log(res);},error:function (error) {console.log(error);}});});//异步上传多个⽂件,带表单参数$("#sub3").click(function () {//将form表单转换为FormData对象var data = new FormData(document.querySelector("#formData3")); $.post({url:'upload/testUpload3',contentType:false, //jQuery不要去设置Content-Type请求头processData:false, //jQuery不要去处理发送的数据cache:false, //不缓存dataType:'json', //返回类型jsondata:data, //表单数据success:function (res) {console.log(res);},error:function (error) {console.log(error);}});});});</script></body></html>下⾯是controller:@Controller@RequestMapping("/upload")public class FileController {/*** 同步⽂件⼀个上传和异步上传⼀个⽂件,共同使⽤这⼀个控制器⽅法* @param request* @param upload* @return* @throws IOException*/@RequestMapping(value = "/testUpload",method = RequestMethod.POST)public String upload(HttpServletRequest request, MultipartFile upload) throws IOException {//获取⽂件的保存路径String path = request.getServletContext().getRealPath("/uploads");//获取上传⽂件的名称String filename = upload.getOriginalFilename();//获取随机字符串String prefix = UUID.randomUUID().toString().replaceAll("-", "");filename = prefix + "_" + filename;//创建⽂件对象File file = new File(path);//判断路径是否存在,不存在则创建if(!file.exists()){file.mkdir();}//上传⽂件upload.transferTo(new File(file,filename));return "success";}/*** 异步⽂件上传和表单数据* @param request* @param upload* @return* @throws IOException*/@RequestMapping(value = "/testUpload2",method = RequestMethod.POST)public @ResponseBody Account upload2(HttpServletRequest request, MultipartFile upload, Account account) throws IOException { //获取⽂件的保存路径String path = request.getServletContext().getRealPath("/uploads");//获取上传⽂件的名称String filename = upload.getOriginalFilename();//获取随机字符串String prefix = UUID.randomUUID().toString().replaceAll("-", "");filename = prefix + "_" + filename;//创建⽂件对象File file = new File(path);//判断路径是否存在,不存在则创建if(!file.exists()){file.mkdir();}//上传⽂件upload.transferTo(new File(file,filename));return account;}/*** 异步多个⽂件上传和表单数据* @param request* @param upload 采⽤数组接收* @return* @throws IOException*/@RequestMapping(value = "/testUpload3",method = RequestMethod.POST)public @ResponseBody Account upload3(HttpServletRequest request, MultipartFile[] upload, Account account) throws IOException { //获取⽂件的保存路径String path = request.getServletContext().getRealPath("/uploads");//创建⽂件对象File file = new File(path);//判断路径是否存在,不存在则创建if(!file.exists()){file.mkdir();}for (MultipartFile multipartFile : upload) {//获取上传⽂件的名称String filename = multipartFile.getOriginalFilename();//获取随机字符串String prefix = UUID.randomUUID().toString().replaceAll("-", "");filename = prefix + "_" + filename;//上传⽂件multipartFile.transferTo(new File(file,filename));}return account;}}public class Account implements Serializable {private int id;private String name;private float money;//getter or setter....}注意事项:上传⽂件时,表单的 enctype 修改为:multipart/form-data;后端使⽤ MultipartFile upload 对象接收,upload 必须和 <input> 的name属性⼀致;上传多个⽂件,给 <input> 添加:multiple=“multiple”效果:更多精彩内容请参考专题,和进⾏学习。

JQGrid之文件上传

JQGrid之文件上传

JQGrid之⽂件上传⽂件/图⽚上传功能,简单总结如下1.引⼊ajaxfileupload.js注意:该⽂件需要在引⼊Jquery之后引⼊下载链接:2.colModel中⽂件上传name设置{name:'cover',index:'cover',edittype:"file",editable:true,editoptions: {enctype: "multipart/form-data"},formatter:function (value,option,rows) {return "<img style='width:30%;height:10s%;' src='${pageContext.request.contextPath}/image/"+rows.cover+"'/>"; }},3.前台编码35 autowidth:true,36 height:'60%',37 rowNum : 3,38 rowList : [2,3,4,5],39 caption : "轮播图的详细信息",40 editurl:'${pageContext.request.contextPath}/banner/oper',//设置编辑表单提交路径41 viewrecords : true,42//recreateForm: true确保每添加或编辑表单是重新创建。

43 }).navGrid('#pager',{edit : true,add : true,del : true,search:false},4445 {46 jqModal:true,closeAfterAdd: true,recreateForm:true,onInitializeForm : function(formid){47 $(formid).attr('method','POST');48 $(formid).attr('action','');49 $(formid).attr('enctype','multipart/form-data');50 },51 afterSubmit:function (response) {52 var status = response.responseJSON.status;53 var id = response.responseJSON.message;54 alert("确认修改")55if(status){56 $.ajaxFileUpload({57 url:"${pageContext.request.contextPath}/banner/upload",58 fileElementId:"cover",59 data:{id:id},60 type:"post",61 success:function () {62 $("#tt").trigger("reloadGrid")63 }64 });65 }66 }67 },6869 {70 jqModal:true,closeAfterEdit: true,recreateForm:true,onInitializeForm : function(formid){71 $(formid).attr('method','POST');72 $(formid).attr('action','');73 $(formid).attr('enctype','multipart/form-data');74 },75 afterSubmit:function (response) {76 var status = response.responseJSON.status;77 var id = response.responseJSON.message;78 alert("确认添加")79if(status){80 $.ajaxFileUpload({81 url:"${pageContext.request.contextPath}/banner/upload",82 fileElementId:"cover",83 data:{id:id},84 type:"post",85 success:function () {86 $("#tt").trigger("reloadGrid")87 }88 });89 }90 }90 }91 }92 );93 })94 </script>95 <body>96 <table id="tt"></table>97 <div id="pager" style="height: 30px"></div>98 </body>99 </html>前台代码4.后台编码1public void upload(String id, MultipartFile cover) throws IOException {2//需要在submit之后进⾏⼀次图⽚路径的修改3 Banner banner = new Banner();4 ("上传图⽚的原始名字"+cover.getOriginalFilename());5 String realPath =httpSession.getServletContext().getRealPath("image");6 cover.transferTo(new File(realPath,cover.getOriginalFilename()));7 banner.setId(id);8 banner.setCover(cover.getOriginalFilename());9 bannerDAO.updateByPrimaryKeySelective(banner);10 }后台代码。

jquery批量上传图片实现代码

jquery批量上传图片实现代码

jquery批量上传图⽚实现代码复制代码代码如下:<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="/1999/xhtml"><head runat="server"><title>upload</title><link href="upload.css" rel="Stylesheet" /></head><body><form><ul><li><button id="SubUpload" onclick="TSubmitUploadImageFile();return false;">确定上传</button>&nbsp;&nbsp;<button id="CancelUpload" class="ManagerButton" onclick="javascript:history.go(-1);">取消</button>&nbsp;&nbsp;<button id="AddUpload" class="ManagerButton" onclick="TAddFileUpload();return false;">增加</button></li></ul><ul id="loadimage"><li><div class="imagelabel">图⽚1:</div><div class="imagepath"><input name="" size="45" id="uploadImg1" type="file" /></div><div class="loadinfo"><span id="uploadImgState1"></span></div></li></ul></form></body></html><script type="text/javascript" src="/JS/jquery-1.3.2-vsdoc.js"></script><script type="text/javascript">var TfileUploadNum = 1; //记录图⽚选择框个数var Tnum = 1; //ajax上传图⽚时索引//增加上传按钮function TAddFileUpload() {var idnum = TfileUploadNum + 1;var str = "<li>";str += "<div class='imagelabel'>图⽚" + idnum + ":</div>";str += "<div class='imagepath'><input name='' size='45' id='uploadImg" + idnum + "' type='file' /></div>";str += "<div class='loadinfo'><span id='uploadImgState" + idnum + "'></span></div>";str += "</li>";$("#loadimage").append(str);TfileUploadNum += 1;}//开始上传function TSubmitUploadImageFile() {document.getElementById("SubUpload").disabled = true;document.getElementById("CancelUpload").disabled = true;document.getElementById("AddUpload").disabled = true;setTimeout("TajaxFileUpload()", 1000); //此为关键代码}//Ajax上传⽅法function TajaxFileUpload() {if (Tnum < TfileUploadNum + 1) {//准备提交处理$("#uploadImgState" + Tnum).html("<img src='/gif/upfileloader.gif'/>");//开始提交$.ajax({type: "POST",url: "Handler.ashx",data: { upfile: $("#uploadImg" + Tnum).val()},success: function(data, status) {var stringArray = data.split("|");//stringArray[0] 成功状态(1为成功,0为失败)//stringArray[1] 上传成功的⽂件名//stringArray[2] 消息提⽰if (stringArray[0] == "1") {//上传成功$("#uploadImgState" + Tnum).html("<img src='/gif/Success.gif' />" + stringArray[1] + "--" + stringArray[2]); }else {//上传出错$("#uploadImgState" + Tnum).html("<img src='/gif/Error.gif' />" + stringArray[1] + "--" + stringArray[2]);}Tnum++;setTimeout("TajaxFileUpload()", 1000);}});}else {document.getElementById("SubUpload").disabled = false;document.getElementById("CancelUpload").disabled = false;document.getElementById("AddUpload").disabled = false;}} </script>复制代码代码如下:<%@ WebHandler Language="C#" Class="Handler" %>using System;using System.Web;using System.IO;using System.Text;using ;public class Handler : IHttpHandler{public void ProcessRequest(HttpContext context){//源图⽚路径string _fileNamePath = "";try{_fileNamePath = context.Request.Form["upfile"];string _savedFileResult = UpLoadFile(_fileNamePath); //开始上传context.Response.Write(_savedFileResult);//返回上传结果}catch{context.Response.Write("0|error|⽂件路径错误");}}/// <summary>/// 保存图⽚/// </summary>/// <param name="fileNamePath"></param>/// <returns></returns>private string UpLoadFile(string fileNamePath){//图⽚格式string fileNameExt = fileNamePath.Substring(fileNamePath.IndexOf('.')).ToLower();if (!CheckFileExt(fileNameExt)) return "0|error|图⽚格式不正确!";//保存路径string toFilePath = "ProductUpload/";//物理完整路径string toFileFullPath = HttpContext.Current.Server.MapPath(toFilePath);//检查是否有该路径没有就创建if (!Directory.Exists(toFileFullPath)){Directory.CreateDirectory(toFileFullPath);}//⽣成将要保存的随机⽂件名string toFileName = GetFileName();//将要保存的完整路径string saveFile=toFileFullPath +toFileName + fileNameExt;///创建WebClient实例WebClient myWebClient = new WebClient();//设定windows⽹络安全认证myWebClient.Credentials = CredentialCache.DefaultCredentials;//要上传的⽂件FileStream fs = new FileStream(fileNamePath, FileMode.Open, FileAccess.Read); BinaryReader r = new BinaryReader(fs);//使⽤UploadFile⽅法可以⽤下⾯的格式myWebClient.UploadFile(saveFile,fileNamePath);return "1|"+toFileName+fileNameExt+"|保存成功.";}/// <summary>/// 检测图⽚类型/// </summary>/// <param name="_fileExt"></param>/// <returns>正确返回True</returns>private bool CheckFileExt(string _fileExt){string[] allowExt = new string[] { ".gif", ".jpg", ".jpeg" };for (int i = 0; i < allowExt.Length; i++){if (allowExt[i] == _fileExt) { return true; }}return false;}/// <summary>/// 得到随机图⽚名/// </summary>/// <returns></returns>public static string GetFileName(){Random rd = new Random();StringBuilder serial = new StringBuilder();serial.Append(DateTime.Now.ToString("yyMMddHHmmssff"));serial.Append(rd.Next(0, 9999).ToString());return serial.ToString();}public bool IsReusable{get{return false;}}}复制代码代码如下:body{font-size: 12pt;}ul{list-style: none;}li{margin: 0px;}#loadimage{width: 860px;overflow: hidden;}.imagelabel{ float: left; width: 60px; height: 25px;} .imagepath{float: left; width: 400px; height: 25px; } .loadinfo{float: left; width: 400px;height: 25px;}。

原生JS和jQuery版实现文件上传功能

原生JS和jQuery版实现文件上传功能

原⽣JS和jQuery版实现⽂件上传功能本⽂实例分享了原⽣JS版和jQuery 版实现⽂件上传功能的例⼦,供⼤家参考,具体内容如下<!doctype html><html lang="zh"><head><meta charset="utf-8"><title>HTML5 Ajax Uploader</title><script src="jquery-2.1.1.min.js"></script></head><body><p><input type="file" id="upfile"></p><p><input type="button" id="upJS" value="⽤原⽣JS上传"></p><p><input type="button" id="upJQuery" value="⽤jQuery上传"></p><script>/*原⽣JS版*/document.getElementById("upJS").onclick = function() {/* FormData 是表单数据类 */var fd = new FormData();var ajax = new XMLHttpRequest();fd.append("upload", 1);/* 把⽂件添加到表单⾥ */fd.append("upfile", document.getElementById("upfile").files[0]);ajax.open("post", "test.php", true);ajax.onload = function () {console.log(ajax.responseText);};ajax.send(fd);}/* jQuery 版 */$('#upJQuery').on('click', function() {var fd = new FormData();fd.append("upload", 1);fd.append("upfile", $("#upfile").get(0).files[0]);$.ajax({url: "test.php",type: "POST",processData: false,contentType: false,data: fd,success: function(d) {console.log(d);}});});</script></body></html>php代码:<?phpif (isset($_POST['upload'])) {var_dump($_FILES);move_uploaded_file($_FILES['upfile']['tmp_name'], 'up_tmp/'.time().'.dat');//header('location: test.php');exit;}>更多精彩内容请参考专题,和进⾏学习。

js实现多文件上传(二)--拖拽上传

js实现多文件上传(二)--拖拽上传
}) </script>
预览:
登录后才能查看或发表评论立即登录或者逛逛博客园首页
js实现多文件上传(二) --拖拽上传
html:
<form > <div class="drag-wrapper"> 请将图片拖到此处 </div>
</form>
css:
<style> .drag-wrapper{ width:100%; height: 300px; border: 4px dashed lightblue; text-align: center; line-height: 300px; color: lightgrey; } .drag-wrapper img{ max-width: 80px; } </style>
event.preventDefault(); //数据在event的dataTransfer对象里 let file = event.originalEvent.dataTransfer.files[0]; //同样用fileReader实现图片上传 let fd = new FileReader(); let fileType = file.type; fd.readAsDataURL(file); fd.onload = function(){
if(/^image\/[jpeg|png|gif|jpg]/.test(fileType)){ $('.drag-wrapper').append('<img src="'+this.result+'"/>')

22个很棒的jQuery文件上传插件

22个很棒的jQuery文件上传插件

22个很棒的jQuery文件上传插件发表于2011-08-04 10:53| 15595次阅读| 来源开源中国社区| 6条评论| 作者红薯文件上传组件ajax框架jquery文件上传jquery插件jquery摘要:文件上传是网站很常见的功能之一,通过使用jQuery可以让上传过程更加人性化,更好的用户体验。

文件上传是网站很常见的功能之一,通过使用jQuery可以让上传过程更加人性化,更好的用户体验。

本文介绍20个jQuery的文件上传插件,其中有一些是教程。

1. PluploadPlupload是一个Web浏览器上的界面友好的文件上传模块,可显示上传进度、图像自动缩略和上传分块。

可同时上传多个文件。

2. The KillersAjax Upload该插件使用XHR 用于上传多个文件,支持上传进度显示,但不支持IE3. SWFUpload jQuery Plugin4. AjaxFileUpload5. UploadifyUploadify简单说来,是基于Jquery的一款文件上传插件。

它的功能特色总结如下:1. 支持单文件或多文件上传,可控制并发上传的文件数2. 在服务器端支持各种语言与之配合使用,诸如PHP,.NET,Java……3. 通过参数可配置上传文件类型及大小限制4. 通过参数可配置是否选择文件后自动上传5. 易于扩展,可控制每一步骤的回调函数(onSelect, onCancel……)6. 通过接口参数和CSS控制外观6. jQuery Multiple File Upload Plugin7. jqUploaderjqUploader是实现文件上传的jQuery插件8. jQuery Form PluginjQuery Form Plugin 是一个扩展表单操作的jQuery插件,直接文件上传表单9. jQuery Form Plugin10. jqswfupload11. uploadprogress12. jQuery File Upload13. Multiple File Upload With Progress Bar Using jQuery14. jQuery.upload一个简单的Ajax 文件上传插件15. Ajax File Upload Script Using jQuery jQuery File Uploader使用iframe来处理上传过程16. jQuery Custom File Upload Input17. Image Upload and Cropping with PHP and Jquery18. PHP & jQuery image upload and crop19. AJAX upload progress bars with jQuery, Django and nginx20. Uploading Files with AJAX21. AJAX Multiple File Upload Form Using jQuery22. FancyUpload – Swiff meets Ajax (v3.0)FancyUpload是一个采用Flash与Ajax(MooTools)技术实现包含上传进度条的多文件上传组件,类似于SWFUpload。

20款最好的jQuery文件上传插件

20款最好的jQuery文件上传插件

20款最好的jQuery⽂件上传插件当它是关于开发⽹络应⽤程序和⽹页的时候,⽂件上传功能的重要性是不容忽视的。

⼀个⽂件上传功能可以让你上传所有类型的⽂件在⽹站上,包括视频,图像,⽂件和更多。

创建⼀个⽂件上传功能,对你的⽹站是不是很难,有⼀点点的理解和⼀些代码,你可以⾃⼰做的。

然⽽,它不再只是简单地将图像上传到托管服务器上。

有⼀个额外的功能,这些都需要这些天。

例如,当⽤户正在上载⽂件时,他可能会⽴即看到⽂件信息,包括预览。

等特⾊种植,多上传,或调整也很重要,这些天。

这也就是为什么随着⽂件上传功能还有需要建⽴⼀个友好的⽤户界⾯。

这是令⼈难以置信的脚本语⾔如jQuery进⼊画⾯。

互联⽹上有⼤量的jQuery⽂件上传插件。

我们精⼼挑选的⼀些,编制了⼀份清单,你不没有冲刷⽹络它。

这些插件都有你需要的⽂件上传。

1.Closifyclosify是⼀个基于jQuery的插件,简化了开发⼈员的任务是创造⼀个动态图像上传。

与closify可以轻松创建任何图像画布(封⾯,简介,或⾃定义横幅)⽆论⼤⼩你定义,智能不够closify插件将调整图像⼤⼩根据你定义的容器与尊重的图像长宽⽐的⼤⼩,然后它开始产⽣⼀个动态的⼩⼯具,给你的能⼒定位/定位你的照⽚充分;保存照⽚所需的位置并提交位置信息到服务器端存储;你选择只删除选中的照⽚照⽚的变化。

2.Peak UploadPeak Upload是⼀个jQuery插件,可以让你轻松地添加多个或单个⽂件上传功能到你的⽹站。

这个插件使⽤HTML5的唯⼀。

3.PlupUploadPlupload这个JavaScript控件可以让你选择Adobe Flash、Google Gears、HTML5、Microsoft Silverlight、Yahoo BrowserPlus或正常表单Form等多种⽅法进⾏⽂件上传。

4.FileDrop.jsFileDrop是⾃包含的跨浏览器的HTML5,legacy,Ajax,JavaScript⽂件的拖放上传。

用jQuery实现文件的上传,后台为spring+mybatis

用jQuery实现文件的上传,后台为spring+mybatis

⽤jQuery实现⽂件的上传,后台为spring+mybatis 1.⾸先为html代码以及js代码<div id="uploadDiv" style="display:none;"><!-- The fileinput-button span is used to style the file input field as button --><span class="btn btn-success fileinput-button"><i class="glyphicon glyphicon-plus"></i><span>⽂件选择</span><!-- The file input field used as target for the file upload widget --><input id="fileupload" type="file" name="file"></span><button id="uploadBtn" class="btn btn-primary disabled">确认上传</button><br><!-- The global progress bar --><div id="progress" class="progress"><div class="progress-bar progress-bar-success"></div></div><!-- The container for the uploaded files --><div id="msgDiv" class="files"></div></div>$("#uploadBtn").click(function(){var dialog = $("#uploadDiv").clone().dialog({title: "附件上传",width : '75%',height : 500,modal : true});$('#fileupload', dialog).fileupload({dataType: 'json',progressall: function (e, data) {var progress = parseInt(data.loaded / data.total * 100, 10);$('#progress .progress-bar', dialog).css('width',progress + '%').html(progress + '%');$("#msgDiv", dialog).html("处理中……");},add: function (e, data) {data.url = "ra/suspiciousCase/uploadTotal";data.submit();$("#uploadBtn", dialog).off('click').on('click', function () {var id = getUrlParam('id');data.url = "ra/suspiciousCase/upload?id="+id;data.submit();setTimeout(function(){handleUploadTable();}, 3000);//延迟执⾏刷新});},done: function (e, data) {var isTotal = data.url.indexOf("uploadTotal") > -1;var tip = isTotal ? "解析成功,请点击“确认上传”" : "上传";var result = data.result;var msg = "<b>" + tip + "</b>"var bar = $('#progress .progress-bar');bar.removeClass("progress-bar-warning progress-bar-success");if(!result.success){msg = "<b>" + tip + "失败:</b>"+result.error;bar.addClass("progress-bar-warning");$("#uploadBtn", dialog).addClass("disabled");}else{bar.addClass("progress-bar-success");msg = "<b>" + tip + "成功:</b>";if(isTotal){$("#uploadBtn", dialog).removeClass("disabled");}}if(result.totalInfo){msg += "<br>";msg += "<b>提⽰信息:</b>" + result.totalInfo;}msg += "<br><b>⽂件名称:</b>" + data.files[0].name;$("#msgDiv", dialog).html(msg);}})})再来是后台代码@Path("/upload")@POST@NoCache@Consumes("multipart/form-data")public ExtJSResponse upload(@Context HttpServletRequest request) {ExtJSResponse resp = new ExtJSResponse(true);final String id = request.getParameter("id");final AmlSuspectcaseAttach attach = new AmlSuspectcaseAttach();boolean isMultipart= ServletFileUpload.isMultipartContent(request);if(isMultipart){//构造⼀个⽂件上传处理对象FileItemFactory factory = new DiskFileItemFactory();ServletFileUpload upload = new ServletFileUpload(factory);@SuppressWarnings("rawtypes")Iterator items;try{checkPermission(Permissions.AML_SUSPECT_CASE);//解析表单中提交的所有⽂件内容items = upload.parseRequest(request).iterator();while(items.hasNext()){FileItem item = (FileItem) items.next();if(!item.isFormField()){//取出上传⽂件的⽂件名称String name = item.getName();("上传⽂件的⼤⼩为:[{}]",item.getSize());//取得上传⽂件以后的存储路径final String suffix = name.substring(stIndexOf('.') + 1, name.length());int fsize = fileSize*1024*1024;if(fileSuffix.contains(suffix)){if(item.getSize() < fsize){Long attachId = null;if(!StringUtils.isEmpty(name)){attach.setName(name);}if(!StringUtils.isEmpty(id)){attach.setCaseid(Long.parseLong(id));attachId = suspectCase.insertAttch(attach);System.out.println("attach:"+attachId);}if(resp.isSuccess()){//上传⽂件以后的存储路径("上传⽂件:[{}]",attachId+"."+suffix);String Path= amlPath + File.separatorChar + attachId;File file =new File(amlPath);//如果⽂件夹不存在则创建if (!file.exists() && !file.isDirectory()){file.mkdir();}//上传⽂件("上传⽂件的路径为:[{}]",Path);File uploaderFile = new File(Path);item.write(uploaderFile);}}else{("上传⽂件⼤⼩不能超过2M");resp.setSuccess(false);resp.setErrorMsg("上传⽂件⼤⼩不能超过2M");}}else{("⽂件格式不正确,请选择doc、docx、xls、xlsx、png、gif、jpg、jpeg、bmp后缀⽂件!");resp.setSuccess(false);resp.setErrorMsg("⽂件格式不正确,请选择doc、docx、xls、xlsx、png、gif、jpg、jpeg、bmp后缀⽂件!"); }}}}catch(Exception e){e.printStackTrace();resp.setSuccess(false);resp.setErrorMsg("⽂件上传失败");}}return resp;}@Path("/uploadTotal")@POST@NoCache@Consumes("multipart/form-data")public ExtJSResponse uploadTotal(@Context HttpServletRequest request) {ExtJSResponse resp = new ExtJSResponse(true);@SuppressWarnings("unused")InputStream instream = null;try {checkPermission(Permissions.AML_SUSPECT_CASE);ServletFileUpload upload = new ServletFileUpload();FileItemIterator fileIterator = upload.getItemIterator(request);while (fileIterator.hasNext()) {FileItemStream item = fileIterator.next();if ("file".equals(item.getFieldName())){instream = item.openStream();break;}}StringBuilder total = new StringBuilder();resp.put("totalInfo", total);} catch (Exception e) {getLogger().warn(e.getMessage(), e);resp.setSuccess(false);resp.setErrorMsg(e.getLocalizedMessage());}return resp;}其中uploadTotal⽅法是在⽂件上传之前先对⽂件进⾏解析,下⾯贴上我的上传效果图,我这⾥是⽤的frame弹窗解析完再点击确认上传之后就完成了。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

用 Jquery plugin 实现---多文件上传 来源:博客圆 时间:2009-05-13 相关文章:  玩透 javascript 弹出窗口  状态栏走马灯效果  JavaScript 教程  操作 cookies 的 js 框架  纯 javascript 联动的例子  JavaScript 的 BASE64  AJAX 技术基础介绍  菜鸟应用 JAVASCRIPT 之 简易网页音乐播放程  结合 JavaScript 与 Web 窗体进行程序  菜鸟应用 JAVASCRIPT 之 简易闹钟程序
[网站建设之]用 Jquery plugin 实现---多文件上传
在 中关于文件的上传有很多种;所谓的上传有有两种含意:第一种:就是说把文件 保存在数据库;第二种就是保存在 一个指定的文件夹下; 今天给大家介绍一所很简单多文件上传方式;通过 JQ Plugin 插件的形式来达到上传文件的 效果;这种文件上传的方式,简单,灵活 只是能过属性的配置就可以完成上传大部分的工作: 项目目录列表:


第一步:引入 Jquery 相关的 JS 文件:
<script src="JQuery/jquery-1[1].3.2-vsdoc2.js" type="text/javascript"></script> --这是 VS2008 智能感知的一个JS文件 <script src="JQuery/jquery-1[1].3.2.js" type="text/javascript"></script> ---这里 JQ中的内库文件,版本是 1.3.2 <script src="JQuery/jquery.MultiFile.js" type="text/javascript"></script> ----这是 JQ Plugin 文件 注:以上三个文件是除第一个外,都必须引用到你的页面文件中,程序才能正确的运行; 第二步:添加 FileUpload 上传文件控件和一个上传 Button; <fieldset style="height: 94px; width: 359px"> <legend>JQuery 多文件上传 </legend> <asp:FileUpload ID="UpFile" runat="server" class="multi" maxlength="2" /> <asp:Button ID="btnUpload" runat="server" Text="UpLoad All" OnClick="btnUpload_Click" /> </fieldset> 说明:这时可以对 FileUpload 上传控件配置属性,属性说明:
属性名 Class maxlength accept
说明 上传类型 上传文件的个数
用例 class=multi maxlength=3
接受上传文件类型 accept=jpg|rar
还可以自定义上传文件列表的样式,在这里我就不一一举出来,


第三步:编写后上传文件的代码:
protected void btnUpload_Click(object sender, EventArgs e) { try { HttpFileCollection hfc = Request.Files; for (int i = 0; i < hfc.Count; i++) { HttpPostedFile hpf = hfc[i]; if (hpf.ContentLength > 0) { hpf.SaveAs(Server.MapPath("MyFile") + "\\" + System.IO.Path.GetFileName(hpf.FileName)); Response.Write("<script>alert('文件上传成功!')</script>"); } } } catch (Exception ex) { throw ex; } }
第四步:运行效果:
从运行效果可以看出,当你上传的文件数等于你属性设置的大小时,上传控件的浏览将变为 不可有状态; 这大大给我们简化了写代码时间; 虽然这篇文章很简单,但希望对大家在以后的项目中有所帮助;















相关文档
最新文档