JQuery+ajax实现批量上传图片
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多图上传插件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:感谢大家的阅读,本文由我司收集整编。
$.ajaxfileupload用法
$.ajaxfileupload用法在Web开发中,文件上传是一种常见的操作,而使用Ajax技术可以实现异步文件上传,提高页面性能和用户体验。
jQuery中的$.ajaxFileUpload方法提供了一种简单易用的方式来实现文件上传功能。
$.ajaxFileUpload方法用于通过Ajax方式上传文件,支持多文件上传和回调函数的使用。
它接受三个参数:文件路径、回调函数和可选配置参数。
通过该方法,可以实现文件上传的异步操作,避免了页面刷新带来的影响,提高了页面性能。
二、用法示例```javascript//创建一个用于上传文件的表单元素varform=$('<form/>',{'method':'POST','enctype':'multipart/form-data'}).appendTo('body');//添加文件输入框varinput=$('<input/>',{'type':'file','name':'file','value':''}).appendTo(form);//触发文件选择器,选择文件input.trigger('click');//添加文件到表单中input.on('change',function(){varfiles=input.prop('files');if(files&&files.length>0){//创建AjaxFileUpload对象varupload=newAjaxFileUpload(form,{//配置选项action:'/upload',//上传接口地址autoSubmit:false,//不自动提交表单responseType:'json',//返回数据类型为JSONfileVal:'file',//文件字段名onComplete:function(data){//上传完成后回调函数console.log(data);//打印返回数据//TODO:处理上传结果,更新页面等操作},onError:function(error){//上传过程中出现错误时回调函数console.log(error);//打印错误信息//TODO:处理上传错误,显示错误提示等操作}});//开始上传文件upload.upload();}else{console.log('请选择文件');//输出提示信息}});```在上述示例中,首先创建了一个表单元素和一个文件输入框,并设置了表单的enctype属性为multipart/form-data,用于多文件上传。
jquery批量上传图片+缩略图+水印
jquery批量上传图片+缩略图+水印图片上传+缩略图+水印处理代码://文件上传Public function _upload( $thumb = false , $thumbWidth = '' , $thumbHeight = '') {$upload = new \Think\Upload();// 实例化上传类$upload->maxSize = 3145728 ;// 设置附件上传大小$upload->exts = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型$upload->savePath = '/' . CONTROLLER_NAME .'/'; // 设置附件上传目录$info = $upload->upload();if(!$info) {return array('status' =>0, 'info'=> $upload->getError() );}else{if( $thumb ) { //生成缩略图$image = new \Think\Image();foreach($info as $file) {$thumb_file = './Uploads/' . $file['savepath'] . $file['savename'];$save_path = './Uploads/' .$file['savepath'] . 'mini_' . $file['savename'];$image->open( $thumb_file )->text('德兴房产','./data/1.otf',30,'#A7AAA4',\Think\Image::IMAGE_WATER_SOUTHWEST)->save( $thumb_file ); $image->open( $thumb_file )->text('德兴房产','./data/1.otf',24,'#A7AAA4',\Think\Image::IMAGE_WATER_SOUTHWEST)->thumb( $thumbWidth, $thumbHeight )->save( $save_path );return array('status' => 1,'savepath' => $file['savepath'],'savename' => $file['savename'],'pic_path' => $file['savepath'] . $file['savename'],'mini_pic' => $file['savepath'] . 'mini_' .$file['savename']);}}else{foreach($info as $file) {return array('status' => 1,'savepath' => $file['savepath'],'savename' => $file['savename'],'pic_path' => $file['savepath'].$file['savename']);}}}}前端主要代码(参考:///code/151.html):<div class="tab-pane" id="tab3"><div class="row"><div class="col-md-12"><div class="tab-pane"><div class="form-group"><input type="file" id="upload" class="form-control input-medium" /></div><div style="width:100%; float:left;padding:10px 20px 20px; background-color:#ccc"><p><ul class="imagelist" id="image_result"></ul></p></div></div></div></div></div> <!-- END #TAB3 --><div class="margin-top-10"><button type="submit" class="btn green ajax-post">确认</button><a href="javascript:" onclick="javascript:history.back(-1);return false;" class="btn default">返回</a></div></div></div></form></div></div></block><block name="foot"><link href="__PUBLIC__/assets/plugins/uploadify/uploadify.css" rel="stylesheet" type="text/css"/><link href="__PUBLIC__/assets/plugins/uniform/css/uniform.default.css" rel="stylesheet" type="text/css"/><script src="__PUBLIC__/assets/plugins/uniform/jquery.uniform.min.js" type="text/javascript" ></script><script src="__PUBLIC__/assets/plugins/uploadify/jquery.uploadify.min.js" type="text/javascript" ></script><script type="text/javascript">$(function(){var sid = "{:session_id()}";$('#upload').uploadify({'swf':'__PUBLIC__/assets/plugins/uploadify/uploadify.swf','buttonText': '选择图片','formData': { 'session_id':sid},'uploader': "{:U('uploadPic')}",'fileTypeDesc':'Image File','fileTypeExts':'*.jpg; *.jpeg; *.gif; *.png','auto' : true,'removeCompleted': false,onUploadSuccess: function(file, data, response) {$('#progress').hide();var result = $.parseJSON(data);//错误处理。
php中使用jqueryuploadify进行多图片上传实例
php中使用jqueryuploadify进行多图片上传实例php中使用jquery uploadify进行多图片上传实例导语:jquery uploadify是一款Ajax风格的'批量图片上传插件,在PHP中使用jquery uploadify很方便,请按照本文介绍的方法和步骤,为你的PHP程序增加jquery uploadify插件的批量上传图片功能。
下面的是店铺为大家搜集的在php中使用jquery uploadify进行多图片上传实例,希望对大家能有所帮助。
本文是以dilicms为基础,为其增加图片上传功能。
1.增加数据表dili_fieldtypes新字段:k=>image,V=>图片上传区域(VACHAR);2.修改application/libraries/dili/Field_behavior.php,在switch中增加如下代码:1case 'image':2$field=array(3'type'=>'VARCHAR',4'constraint'=>255,5'default'=>' '6);7break;3. 修改application/libraries/dili/Form.php 并且增加如下代码:1function _image($fileld,$default){2//$type= 'type=hidden';3//$width=($field['width'] ? $field['width'] : '570') .'px;';4//$height=($field['height'] ? $field['height'] : '415') .'px;';5return ;6}4.在content_form.php和category_content_form.php中增加判断代码:0102 if($v['type']=="image"):03?>04050607上传08取消上传0910" value=""/>11" value=""/>12asset/js/uploadify/uploadify.css" type="text/css" rel="stylesheet" />1314426. 新建photo.php文件:0102if ( ! defined('BASEPATH')) exit('No direct script access allowed');03date_default_timezone_set('Asia/Shanghai');04class Photo extends Front_Controller{05 public function __construct()06 {07 parent::__construct();08 }09 function _getFilePath()10 {11 $path="attachments/".date("Y")."/";12 if(!file_exists($path)){13 mkdir($path,'777');15 $path.=date("m")."/";16 if(!file_exists($path)){17 mkdir($path,'777');18 }19 return $path;20 }21 function _creat_photothumbs($FileName,$setW){22 $IMGInfo= getimagesize($FileName);23 if(!$IMGInfo) return false;24 if($IMGInfo['mime']== "image/pjpeg" || $IMGInfo['mime']=="image/jpeg"){25 $ThisPhoto= imagecreatefromjpeg($FileName);26 }elseif($IMGInfo['mime']== "image/x-png" || $IMGInfo['mime']== "image/png"){27 $ThisPhoto= imagecreatefrompng($FileName);28 }elseif($IMGInfo['mime']== "image/gif"){29 $ThisPhoto=imagecreatefromgif($FileName);30 }31 $width=$IMGInfo['0'];32 $height=$IMGInfo['1'];33 $scale=$height/$width;34 $nw=$setW;35 $nh=$nw*$scale;36 $NewPhoto=imagecreatetruecolor($nw,$nh);37imagecopyresampled($NewPhoto,$ThisPhoto,0,0,0,0,$nw,$nh,$ width,$height);38 ImageJpeg ($NewPhoto,$FileName);39 return true;41 function _savephoto_post(){42 $dest_dir =$this->_getFilePath();43 if (!empty($_FILES)) {44 $date = date('Ymd');45 //$dest_dir =$this->_getFilePath();46 $photoname = $_FILES["Filedata"]['name'];47 $phototype = $_FILES['Filedata']['type'];48 $photosize = $_FILES['Filedata']['size'];49 $fileInfo=pathinfo($photoname);50 $extension=$fileInfo['extension'];51 $newphotoname = date("YmdHis").mt_rand(10000,99999).'.'.$extension;52 $dest=$dest_dir.$newphotoname;53 //move_uploaded_file($_FILES['Filedata']['tmp_name'], iconv("UTF-8","gb2312",$dest));54 move_uploaded_file($_FILES['Filedata']['tmp_name'], $dest);55 //chmod($dest, 0755);56 //如果宽度大于600则要进行裁剪57 $arr=getimagesize($dest);58 if($arr[0]>600){59 $thumb_w=600;60 $this->_creat_photothumbs($dest,$thumb_w);61 }62 //生成缩略图63 $config2['image_library'] = 'gd2';64 $config2['source_image'] = $dest;65 $config2['create_thumb'] = TRUE;66 $config2['maintain_ratio'] = TRUE;67 $config2['width'] = 170;68 $config2['height'] = 150;69 $config2['master_dim']="width";70 $config2['thumb_marker']="_1";71 $this->load->library('image_lib', $config2);72 $this->image_lib->resize();73 echo $dest;74 }75 }76}77?>下载全文。
jquery实现上传图片功能
jquery实现上传图⽚功能本⽂实例为⼤家分享了jquery实现上传图⽚功能的具体代码,供⼤家参考,具体内容如下代码:<!DOCTYPE html><html><head><meta charset="UTF-8"><title>点击头像上传图⽚</title><style>*{margin:0;padding: 0;}div,#avarimgs,#xdaTanFileImg{width: 100px;height: 100px;}div{margin:50px auto;position: relative;}#xdaTanFileImg{position: absolute;top: 0;left: 0;opacity: 0;}</style></head><body><div><input type="file" name="pclogo" id="xdaTanFileImg" onchange="xmTanUploadImg(this)" accept="image/*"><img src="/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=3787285033,4172246344&fm=26&gp=0.jpg" class="img-circle img-thumbnail img-responsive" id="avarimgs"> </div></body><script src="/jquery-2.1.1.min.js"></script><script type="text/javascript">if (typeof FileReader == 'undefined') {document.getElementById("xmTanDiv").InnerHTML = "<h1>当前浏览器不⽀持FileReader接⼝</h1>";document.getElementById("xdaTanFileImg").setAttribute("disabled", "disabled");}//选择图⽚,马上预览function xmTanUploadImg(obj) {console.log(obj)var file = obj.files[0];console.log(obj);console.log(file);console.log("file.size = " + file.size);var reader = new FileReader();reader.onloadstart = function (e) {console.log("开始读取....");}reader.onprogress = function (e) {console.log("正在读取中....");}reader.onabort = function (e) {console.log("中断读取....");}reader.onerror = function (e) {console.log("读取异常....");}reader.onload = function (e) {console.log("成功读取....");var img = document.getElementById("avarimgs");img.src = e.target.result;//或者 img.src = this.result; //e.target == this}reader.readAsDataURL(file)}</script></html>以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。
ajaxFileupload实现多文件上传功能
ajaxFileupload实现多⽂件上传功能打开google 搜索"ajaxFileupload' ‘多⽂件上传"可以搜到许许多多类似的,那我为什么还要写⼀下呢?⼀个是对之前⼤神的贡献表⽰感谢;⼆个是⾃⼰知识的总结;三个是⾃⼰在原有的基础上改动了下,在此记录,可能帮助其他朋友。
⽤过这个插件的都知道这个插件的基本⽤法,我就不废话,直接上代码。
我需要实现多个⽂件上传,之前的做法是定义多个不同id的input,然后把ajaxfileuplod⽅法放在for循环⾥,这个⽅法是在⽹上看到的,我觉得不怎么好,后⾯在⽹上找到的,就⾼级点了,直接改源码(因为作者好久没有跟新了,也确实满⾜不了要求了)。
接下来看看我是怎么改的。
引⽤⽹上的做法:1、看没有修改前的代码var oldElement = jQuery('#' + fileElementId);var newElement = jQuery(oldElement).clone();jQuery(oldElement).attr('id', fileId);jQuery(oldElement).before(newElement);jQuery(oldElement).appendTo(form);很容易看出,这个就是把id为什么的input加到from⾥去,那么要实现多个⽂件上传,就改成下⾯的样⼦:if(typeof(fileElementId) == 'string'){fileElementId = [fileElementId];}for(var i in fileElementId){var oldElement = jQuery('#' + fileElementId[i]);var newElement = jQuery(oldElement).clone();jQuery(oldElement).attr('id', fileId);jQuery(oldElement).before(newElement);jQuery(oldElement).appendTo(form);}这样改之后,初始化的代码就要这么写:$.ajaxFileUpload({url:'/ajax.php',fileElementId:['id1','id2']//原先是fileElementId:'id' 只能上传⼀个});到这⾥,确实可以上传多个⽂件,但是对于我来说新问题⼜来,多个id,我的界⾯的⽂件不是固定的,是动态加载的,那么id 要动态⽣成,我觉得太⿇烦,为什么不取name呢?然后把以上代码改为如下:if(typeof(fileElementId) == 'string'){fileElementId = [fileElementId];}for(var i in fileElementId){//按name取值var oldElement = jQuery("input[name="+fileElementId[i]+"]");oldElement.each(function() {var newElement = jQuery($(this)).clone();jQuery(oldElement).attr('id', fileId);jQuery(oldElement).before(newElement);jQuery(oldElement).appendTo(form);});}这样改了那么就可以实现多组多个⽂件上传,接下来看我是怎么应⽤的。
PHP+Ajax+JS实现多图上传_
PHP+Ajax+JS实现多图上传_本文实例在wap站项目中需要做一个ajax多图片上传,结合js插件做了一个,供大家参考,具体内容如下/* ajax 上传图片 */var num = 0;// 点击删除图片function onDelete(num){if($("#"+num).attr('src')!="__PUBLIC__/Home/images/ jiazai.gif" $("#"+num).attr('src')!=""){if(confirm("确认删除吗")){$("#a"+num).remove();}else{}}}$(function(){$("#file0").bind("change",function(){clickUpload(num);});function clickUpload(num){var imgObject = document.getElementById('file0'); // 文件对象$("#yulan").append("a id='a"+num+"' onclick='onDelete("+num+")' href='javascript:;' img id='"+num+"' width='75' height='75' src='__PUBLIC__/Home/images/jiazai.gif'//a");// $("#yulan").append("li id='a"+num+"' img id='"+num+"' src='__PUBLIC__/Home/images/jiazai.gif' /a href='javascript:;' onclick='onDelete("+num+")'删除/a/li");var getImageSrc = getFullPath(imgObject); // 本地路径// 实例化image对象var pos = stIndexOf(".");var lastname = getImageSrc.substring(pos, getImageSrc.length) // 图片后缀if(lastname!=".jpg" lastname!=".png" lastname!=".jpeg" lastname!='.gif'){$("#a"+num).remove();alert("请选择一张图片");}else{ajaxFileUpload(num);$("#file0").unbind("change").bind("change",function (){clickUpload(num);});}num++;}function getFullPath(obj) { //得到图片的完整路径 if (obj) {if (erAgent.indexOf("MSIE") = 1) {obj.select();return document.selection.createRange().text; }else if (erAgent.indexOf("Firefox") = 1) { if (obj.files) {return obj.files.item(0).getAsDataURL();}return obj.value;}return obj.value;}}function ajaxFileUpload(num) {$.ajaxFileUpload({url: 'http://xxxx/updateImg', //用于文件上传的服务器端恳求地址secureuri: false, //是否需要平安协议,一般设置为falsefileElementId: 'file0', //文件上传域的IDdataType: 'json', //返回值类型一般设置为json success: function (data) //服务器胜利响应处理函数{var jsonText = data;console.log(jsonText);if(jsonText['status']==1){if(jsonText['info']!=""){console.log(jsonText['info']); $("#"+num).attr("src","__PUBLIC__//Admin/Upload/"+jsonText['info']);var images = $("#img").val();if(images!=""){$("#img").val(images+","+jsonText['info']);}else{$("#img").val(images+""+jsonText['info']);}}}else{$("#a"+num).remove();// alert("图片上传失败");}},error: function (data,e)//服务器响应失败处理函数{alert(e);}})}});以上就是本文的全部内容,盼望对大家学习php程序设计有所关心。
通过ajax、servlet实现图片的上传功能
通过ajax、servlet实现图⽚的上传功能经测试可⾏,本⼈上传的地址是要在C盘的⽬录下建⼀个"Image"⽂件夹(当然可以⾃⾏创建)jsp页⾯:<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%><!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=UTF-8"><title>Insert title here</title></head><body><!--这⾥⽂件上传实例--><div class="container"><div class="panel-heading">分段读取⽂件:</div><div class="panel-body"><input type="file" id="file"/></div></div></body><script type="text/javascript">/** 分段读取⽂件为blob ,并使⽤ajax上传到服务器* 分段上传exe⽂件会抛出异常*/var fileBox = document.getElementById('file');file.onchange = function() {// 获取⽂件对象var file = this.files[0];var reader = new FileReader();var step = 1024 * 1024;var total = file.size;var cuLoaded = 0;("⽂件⼤⼩:" + file.size);var startTime = new Date();// 读取⼀段成功reader.onload = function(e) {// 处理读取的结果var loaded = e.loaded;// 将分段数据上传到服务器uploadFile(reader.result, cuLoaded, function() {('loaded:' + cuLoaded + 'current:' + loaded);// 如果没有读完,继续cuLoaded += loaded;if (cuLoaded < total) {readBlob(cuLoaded);} else {console.log('总共⽤时:'+ (new Date().getTime() - startTime.getTime())/ 1000);cuLoaded = total;}});}// 指定开始位置,分块读取⽂件function readBlob(start) {// 指定开始位置和结束位置读取⽂件// ('start:' + start);var blob = file.slice(start, start + step);reader.readAsArrayBuffer(blob);}// 开始读取readBlob(0);// 关键代码上传到服务器function uploadFile(result, startIndex, onSuccess) {var blob = new Blob([ result ]);// 提交到服务器var fd = new FormData();fd.append('file', blob);fd.append('filename', );fd.append('loaded', startIndex);var xhr = new XMLHttpRequest();xhr.open('post', 'http://localhost:8080//uploadtwo/UploadServlet',true);xhr.onreadystatechange = function() {if (xhr.readyState == 4 && xhr.status == 200) {// var data = eval('(' + xhr.responseText + ')');(xhr.responseText);if (onSuccess)}}// 开始发送xhr.send(fd);}}</script></html>后端UploadServlet:package com.servlet;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.RandomAccessFile;import java.text.SimpleDateFormat;import java.util.Date;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;@WebServlet("/UploadServlet")public class UploadServlet extends HttpServlet {private static final long serialVersionUID = 1L;protected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {try {// 获取客户端传过来图⽚的⼆进制流InputStream stream = request.getInputStream();// 以当前时间戳为图⽚命名SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");String strCurrentTime = df.format(new Date());//最终⽂件存储位置String imagePath = "C://Image/" + strCurrentTime + ".png";// 这⾥的⽂件格式可以⾃⾏修改,如.jpgFileOutputStream fos = new FileOutputStream(imagePath);byte[] bbuf = new byte[32];int hasRead = 0;while ((hasRead = stream.read(bbuf)) > 0) {fos.write(bbuf, 0, hasRead);// 将⽂件写⼊服务器的硬盘上}fos.close();stream.close();/** 但是需要注意,采⽤这种原始的⽅式写⼊⽂件时,你会发现被写⼊的⽂件内容前4⾏并⾮是读取⽂件的真正内容, * 从第四⾏开始才是正⽂数据。
JQuery+ajax实现批量上传图片
在网上搜索了一下,发现以jquery+ajax方式实现单张图片上传的代码是有的,但实现批量上传图片的程序却没搜索到,于是根据搜索到的代码,写了一个可以批量上传的。
先看效果图点击增加按钮,会增加一个选择框,如下图:选择要上传的图片,效果图如下:上传成功如下图:下面来看代码:前台html主要代码:<button id="SubUpload" class="ManagerButton"onClick="TSubmitUploadImageFile();return false;">确定上传</button> <button id="CancelUpload" class="ManagerButton" onClick="javascript:history.go(-1);">取消</button> <button id="AddUpload" class="ManagerButton"onClick="TAddFileUpload();return false;">增加</button><tr><td class="tdClass">图片1:</td><td class="tdClass"><input name="" size="60" id="uploadImg1" type="file" /><span id="uploadImgState1"></span></td></tr>因为用了JQuery,所以你完全可以把click事件放在js文件中“增加”按钮js代码:var TfileUploadNum=1; //记录图片选择框个数var Tnum=1; //ajax上传图片时索引function TAddFileUpload(){var idnum = TfileUploadNum+1;var str="<tr><td class=’tdClass’>图片"+idnum+":</td>";str += "<td class=’tdClass’><input name=’’ size=’60’id=’uploadImg"+idnum+"’ type=’file’ /><spanid=’uploadImgState"+idnum+"’>";str += "</span></td></tr>";("#imgTable").append(str);TfileUploadNum += 1;}“确定上传”按钮js代码:function TSubmitUploadImageFile(){M("SubUpload").disabled=true;M("CancelUpload").disabled=true;M("AddUpload").disabled=true;setTimeout("TajaxFileUpload()",1000);//此为关键代码}关于setTimeout("TajaxFileUpload()",1000);这句代码:因为所谓的批量上传,其实还是一个一个的上传,给用户的只是一个假象。
WEB页面通过ajax进行图片上传实例(附代码)
WEB页⾯通过ajax进⾏图⽚上传实例(附代码)背景:公司需要⼀个签约页⾯,⽀持拍照或选择图⽚上传,应⽤场景主要在⼿机端.页⾯代码:1 <!DOCTYPE html>2 <html>3 <head >4 <meta charset="utf-8" name="viewport" content="width=device-width, initial-scale=0.8 minimum-scale=0.5, maximum-scale=2.0, user-scalable=yes"/>5 <title></title>6 <script src="js/jquery-1.12.4.min.js" type="text/javascript" charset="utf-8"></script>7 <link rel="stylesheet" type="text/css" href="css/index.css"/>8 </head>9 <body>10 <header>11 <!-- <a href="#" class="logo"></a> -->12 <div class="desc">欢迎签约</div>13 </header>14 <section>15 <form id="upload-form" enctype="multipart/form-data">16 <div class="register-box">17 <label for="username" class="other_label">真实姓名18 <input maxlength="20" name ="shortName" type="text" placeholder="输⼊真实姓名"/>19 </label>20 <div class="tips">2122 </div>23 </div>24 <div class="register-box">25 <label for="username" class="other_label">证件号码26 <input maxlength="20" name = "crpIdNo" type="text" placeholder="输⼊证件号码"/>27 </label>28 <div class="tips">2930 </div>31 </div>32 <div class="register-box">33 <label for="username" class="other_label">⼿机号码34 <input maxlength="20" name = "mobilePhone" type="text" placeholder="输⼊⼿机号"/>35 </label>36 <div class="tips">3738 </div>39 </div>40 <div id="checkResult"></div>41 <div class="register-box">42 <label for="username" class="other_label">银⾏卡号43 <input maxlength="20" name = "bankNumber" type="text" placeholder="输⼊银⾏卡号"/>44 </label>45 <div class="tips">4647 </div>48 </div>49 <!-- ⾝份证正⾯ -->50 <div class="register-box">51 <!-- capture="camera" -->52 <label for="username" class="other_label">⾝份证正⾯53 <input maxlength="20" id = "idcard_positive" name = "idcard_positive" type="file" accept="image/*" placeholder="⾝份证正⾯"/>54 </label>55 <div class="tips">5657 </div>58 </div>59 <!-- ⾝份证反⾯ -->60 <div class="register-box">61 <label for="username" class="other_label">⾝份证反⾯62 <input maxlength="20" id = "idcard_reverse" name = "idcard_reverse" type="file" accept="image/*" placeholder="⾝份证反⾯"/>63 </label>64 <div class="tips">6566 </div>67 </div>68 <div class="arguement">69 <input type="checkbox" id="xieyi"/>70 阅读并同意71 <a href="#">《服务合作协议》</a>72 <div class="tips">7374 </div>76 </div>7778 <div class="submit_btn">79 <button type="button" onclick="go()" id="submit_btn">⽴即签约</button>80 </div>81 </form>82 </section>83 <script src="js/index.js" type="text/javascript" charset="utf-8"></script>8485 </body>86 </html>js代码:<script type="text/javascript">$(function(){//聚焦失焦input$('input').eq(0).focus(function(){if($(this).val().length==0){$(this).parent().next("div").text("⽀持中⽂,字母,数字,'-','_'的多种组合");}});//input各种判断//姓名:$('input').eq(0).blur(function(){if($(this).val().length==0){$(this).parent().next("div").text("真实姓名不能为空");$(this).parent().next("div").css("color",'red');}});//⾝份证$('input').eq(1).blur(function(){if($(this).val().length==0){$(this).parent().next("div").text("⾝份证号不能为空");$(this).parent().next("div").css("color",'red');}}); //银⾏卡$('input').eq(3).blur(function(){if($(this).val().length==0){$(this).parent().next("div").text("银⾏卡不能为空");$(this).parent().next("div").css("color",'red');}});});function go(){console.log("点击提交按钮");if($("#xieyi")[0].checked){for(var j=0 ;j<4;j++){if($('input').eq(j).val().length==0){$('input').eq(j).focus();if(j==4){$('input').eq(j).parent().next().next("div").text("此处不能为空");$('input').eq(j).parent().next().next("div").css("color",'red');return;}$('input').eq(j).parent().next(".tips").text("此处不能为空");$('input').eq(j).parent().next(".tips").css("color",'red');return;}};var form = document.getElementById("upload-form");//获取表单的数据var formdata = new FormData( form );//格式化表单数据console.log("格式化表单数据完成"+formdata);$.ajax({//请求⽅式type:'POST',processData: false,// 告诉jQuery不要去处理发送的数据contentType: false,// 告诉jQuery不要去设置Content-Type请求头/* dataType: 'json', */ //设置为返回的数据类型//发送请求的地址url:'http://localhost:8095/hk_partner/SignContractAction/SignContract.action',data:formdata,success: function(result){console.log("响应成功");}});console.log("ajax请求完成");}else{$("#xieyi").next().next(".tips").text("请阅读协议");$("#xieyi").next().next(".tips").css("color",'red');e.preventDefault();return;}}</script> 后端代码:import org.springframework.web.multipart.MultipartFile;import org.springframework.web.multipart.MultipartHttpServletRequest;public void SignContract(HttpServletRequest request,HttpServletResponse response) {String shortName = request.getParameter("shortName");String bankNumber = request.getParameter("bankNumber");String crpIdNo = request.getParameter("crpIdNo");String mobilePhone = request.getParameter("mobilePhone");MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;MultipartFile positive = mRequest.getFile("idcard_positive");//⾝份证正⾯MultipartFile reverse = mRequest.getFile("idcard_reverse");//⾝份证反⾯try {if(positive.getSize()==0 ) {outPrint(response,"需上传⾝份证正⾯");return;};if(reverse.getSize()==0) {outPrint(response,"需上传⾝份证正⾯");return;};}catch (Exception e) {return;}}public static void outPrint(HttpServletResponse response,Object obj) throws IOException{response.setContentType("text/html;charset=UTF-8");response.setHeader("progma","no-cache");response.setHeader("Cache-Control","no-cache");PrintWriter out = response.getWriter();out.print(obj);out.flush();out.close();}1.页⾯和js部分:<meta charset="utf-8" name="viewport" content="width=device-width, initial-scale=0.8 minimum-scale=0.5, maximum-scale=2.0, user-scalable=yes" />描述:⾃适应设备宽度,初始化缩放倍率0.8,最⼩缩放0.5,最⾼2.0.⽤户缩放可调.关于form的enctype属性.描述如下<form id="upload-form" enctype="multipart/form-data">值描述application/x-www-form-urlencoded在发送前编码所有字符(默认)multipart/form-data不对字符编码。
Ajax实现图片上传并预览功能
Ajax实现图⽚上传并预览功能先给⼤家展⽰下效果图,⼤家感觉不错,请参考实现代码。
最近在使⽤ThinkPHP5开发项⽬中客户有⼀个需求是在图⽚上传时附带预览功能。
虽然现在有很多的插件能实现,但是还是觉得⾃⼰写⽐较好。
我们知道,图⽚上传需要⼀个input:file表单<input type='file' name='pic'>当我们点击表单的时候提⽰选择需要上传的图⽚。
但是此需求我们分析⼀下,可以在点击图⽚的时候使⽤JS实现预览功能,并且楼主也是这样做的。
代码如下:function getFileUrl(sourceId) {var url;url = window.URL.createObjectURL(document.getElementById(sourceId).files.item(0));return url;}function preImg(sourceId, targetId) {var url = getFileUrl(sourceId);var imgPre = document.getElementById(targetId);imgPre.src = url;}效果如下:但是这样的话会涉及很多兼容问题。
所以就想到了Ajax,在图⽚上传时,使⽤Ajax技术。
将图⽚上传到服务器,再由服务器返回给我们图⽚的上传地址,然后添加到img标签中去。
过程虽然⿇烦了点,但是亲测不会有兼容问题。
需要发送Ajax请求的话,当然input:file表单是不能实现我们的需求的,因此,我们需要给表单关联⼀个单击事件去帮我们进⾏Ajax请求并选择图⽚<form id="form1"><label for="exampleInputEmail1">头像</label><input type="button" value="上传图⽚" onclick="f.click()" class="btn_mouseout"/><br><p><input type="file" id="f" name="f" onchange="sc(this);" style="display:none"/></p></form><div id="result"></div>当我们点击上传图⽚这个button按钮时触发input:file选择图⽚实现Ajax上传<script>function sc(){var animateimg = $("#f").val(); //获取上传的图⽚名带//var imgarr=animateimg.split('\\'); //分割var myimg=imgarr[imgarr.length-1]; //去掉 // 获取图⽚名var houzui = stIndexOf('.'); //获取 . 出现的位置var ext = myimg.substring(houzui, myimg.length).toUpperCase(); //切割 . 获取⽂件后缀var file = $('#f').get(0).files[0]; //获取上传的⽂件var fileSize = file.size; //获取上传的⽂件⼤⼩var maxSize = 1048576; //最⼤1MBif(ext !='.PNG' && ext !='.GIF' && ext !='.JPG' && ext !='.JPEG' && ext !='.BMP'){yer.msg('⽂件类型错误,请上传图⽚类型');return false;}else if(parseInt(fileSize) >= parseInt(maxSize)){yer.msg('上传的⽂件不能超过1MB');return false;}else{var data = new FormData($('#form1')[0]);$.ajax({url: "{:url('User/uppic')}",type: 'POST',data: data,dataType: 'JSON',cache: false,processData: false,contentType: false}).done(function(ret){if(ret['isSuccess']){var result = '';var result1 = '';// $("#show").attr('value',+ ret['f'] +);result += '<img src="' + '__ROAD__' + ret['f'] + '" width="100">';result1 += '<input value="' + ret['f'] + '" name="user_headimg" style="display:none;">';$('#result').html(result);$('#show').html(result1);layer.msg('上传成功');}else{layer.msg('上传失败');}});return false;}}</script>这⾥我们采⽤FormData对⾯进⾏表单提交,然后服务器端接收public function uppic(){$file = request()->file('f');$info = $file->move(ROOT_PATH . 'public/uploads/avatar');$a=$info->getSaveName();$imgp= str_replace("\\","/",$a);$imgpath='uploads/avatar/'.$imgp;$banner_img= $imgpath;$response = array();if($info){$response['isSuccess'] = true;$response['f'] = $imgpath;}else{$response['isSuccess'] = false;}echo json_encode($response);}这⾥会返回图⽚上传的url路径:$response['f] = $imgpath;现在我们要做的就是将这个url写进前台HTML部分进⾏⼀个显⽰<div class="form-group"><!-- 将Ajax上传的图⽚路径添加到数据库 --><div id="show"></div></div>在JS中添加$('#show').html(result1);总结以上所述是⼩编给⼤家介绍的Ajax实现图⽚上传并预览功能,希望对⼤家有所帮助,如果⼤家有任何疑问请给我留⾔,⼩编会及时回复⼤家的。
php+ajax+h5实现ajax图片上传
php+ajax+h5实现ajax图⽚上传html页⾯代码<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Title</title><script type="text/javascript" src="__PUBLIC__/home/js/jquery-1.11.0.js"></script></head><body><form class="form-horizontal" role="form" id="myForm"action="/index/fileupsend" method="post"enctype="multipart/form-data">选择⽂件:<input type="file" id="file1" /><br /><input type="button" id="upload" value="上传" /><span id="imgWait"></span></form><script>$(function () {$("#upload").click(function () {$("#imgWait").html("上传中");var formData = new FormData();formData.append("myfile", document.getElementById("file1").files[0]);$.ajax({url: "/Home/index/fileupsend",type: "POST",data: formData,/***必须false才会⾃动加上正确的Content-Type*/contentType: false,/*** 必须false才会避开jQuery对 formdata 的默认处理* XMLHttpRequest会对 formdata 进⾏正确的处理*/processData: false,success: function (data) {if(data){alert("上传成功!");}$("#imgWait").html("上传成功");},error: function () {alert("上传失败!");$("#imgWait").hide();}});});});</script></body></html>php代码public function fileupsend(){$type_pic = $this->file_upload('1',array('jpg', 'gif', 'png', 'jpeg'),'filetest','myfile');echo $type_pic['img_path'];}。
如何用input标签和jquery实现多图片的上传和回显功能
如何⽤input标签和jquery实现多图⽚的上传和回显功能本⽂主要记录如何⽤input标签和jquery实现多图⽚的上传和回显,不会涉及后端的交互,⼤概的效果看图效果图我们从零来做⼀个这样的demo第⼀步:我们先完善⼀下我们的页⾯,默认的input-file标签⾮常丑,我们美化⼀下它,不会的可以百度⼀下,就是外⾯套个盒⼦,设置input的opacity为0,然后外⾯的盒⼦设计成我们喜欢的样式即可,我就随便做了⼀下。
⼤概的样式还是放⼀下源码,只谈效果,不放源码的都是耍流氓这是body<body><div class="uploadImgBtn" id="uploadImgBtn"><input class="uploadImg" type="file" name="file" multiple id="file"></div></body>这是css的样式.uploadImgBtn {width: 100px;height: 100px;cursor: pointer;position: relative;background: url("img/plus.png") no-repeat;-webkit-background-size: cover;background-size: cover;}.uploadImgBtn .uploadImg {position: absolute;right: 0;top:0;width: 100%;height: 100%;opacity: 0;cursor: pointer;}//这是⼀个⽤做回显的盒⼦的样式.pic{width: 100px;height: 100px;}.pic img {width: 100%;height: 100%;}代码的量并没有多少,接下来我们就分析⼀下如何让图⽚回显;我知道有两种⽅式,⼀种是先上传到服务器,并返回该图⽚的url,然后渲染在页⾯中;另⼀种呢,是利⽤h5的FileReader对象直接在本地预览图⽚,⽤户确认后再上传服务器。
PHP+jQuery+Ajax仿淘宝多上传按钮单文件上传
PHP+jQuery+Ajax仿淘宝多上传按钮单文件上传PHP+jQuery+Ajax仿淘宝多上传按钮单文件上传如何做一个仿淘宝多上传的`按钮单文件上传呢?下面是由店铺为大家整理的PHP+jQuery+Ajax仿淘宝多上传按钮单文件上传,喜欢的可以收藏一下!了解更多详情资讯,请关注店铺!其代码如下:上传表单<form class="imageform" method="post" enctype="multipart/form-data" action="upload.php"><div class="up_status" style="display:none"><img src="loader.gif" alt="uploading"/></div><div class="btn up_btn"><span>添加图片</span><input class="photoimg" type="file" name="photoimg"></div></form><div class="preview_img"></div>引入样式和上传插件jquery.wallform.js<link rel="stylesheet" type="text/css" href="css/style.css" /><script type="text/javascript" src="/js/jquery/1.7.2/jquery.min.js"></scri pt><script type="text/javascript" src="jquery.wallform.js"></script>jQuery$("body").on("change", ".photoimg",function() {var obj = $(this);var imageForm = obj.parents(".imageform");var preview_img = imageForm.next(".preview_img");var btn = imageForm.find(".up_btn");imageForm.ajaxForm({target: preview_img,beforeSubmit: function() {imageForm.next("div.preview_img").html(""); preview_img.hide();btn.hide();},success: function() {preview_img.show();btn.show();},error: function() {btn.show();preview_img.hide();}}).submit();});PHP上传 upload.phpif (isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST") {$name = $_FILES['photoimg']['name'];$size = $_FILES['photoimg']['size'];if (empty($name)) {echo '请选择要上传的图片';exit;}$ext = extend($name);if (!in_array($ext, $extArr)) {echo '图片格式错误!';exit;}if ($size > (1000 * 1024)) {echo '图片大小不能超过1M';exit;}$image_name = time() . rand(100, 999) . "." . $ext;$tmp = $_FILES['photoimg']['tmp_name'];if (move_uploaded_file($tmp, $path . $image_name)) {echo '<img src="' . $path . $image_name . '" class="preview">';} else {echo '上传出错了!';}exit;}。
ajax上传
上传概述上传类使用ORG类库包中的Net.UpdateFile类,ThinkPHP内置的Action操作里面(主要是insert和update操作,其他操作可以相应实现)实现了自动识别是否存在文件上传,如果存在会自动进行处理。
而上传类要做的仅仅是文件上传的过程,其他功能需要依赖系统类库或者相应类库。
系统对文件上传设置了很多灵活的参数以便进行更细致的控制。
下面我们通过几种常用的例子分别来描述下如何使用UploadFile类。
目前ThinkPHP0.9.5版本的上传类包含的功能如下(有些功能需要结合ThinkPHP系统其他类库):1、基本上传功能2、批量上传3、Ajax方式上传4、自动生成图片缩略图5、自定义参数上传基本上传功能基本上,在ThinkPHP中简单的上传功能无需进行特别处理,而全部有内置操作实现了。
要做的仅仅是在表单中添加文件上传框和设置enctype="multipart/form-data"属性即可。
当然,这和框架的架构和数据结构有关,因为ThinkPHP的上传数据表是单独的,上传文件数据表中有两个关键的用于记录对应数据的字段:module和recordId,其实module也就是某个数据表,而recordId也就是该数据表对应的数据ID。
在其他任何需要上传的数据表中可以方便地查询到属于自己的附件列表,就是采用这种机制和结构,令得ThinkPHP的上传变得简化了。
下面就是实现代码:1.<form METHOD=POST action="__URL__/action/"enctype="multipart/form-data" >2.<INPUT TYPE="text" NAME="name" > INPUT TYPE="text" NAME="email" >3.<INPUT TYPE="file" name="photo" > INPUT TYPE="submit" value="保存" >4.</form>复制代码上面的表单,在保存用户数据的同时包括了一个照片文件上传,使用普通方式提交到后台后,系统自动会把用户数据保存在用户数据表中,而把上传的文件保存到附件数据表,并记录了对应的用户数据表的名称和编号。
Ajax+PHP+jQuery图片截图上传
Ajax+PHP+jQuery图片截图上传一、功能分析用户直接上传图片,点击"上传"按钮之后,在图片预览图内可预览图片,然后进行图片的裁剪前预览,当点击"裁剪"按钮时确定裁剪图片,并在"裁剪结果"区域显示裁剪后的效果。
(说明:我是将上传文件保存在"/uploads"文件夹中,而截图结果放在"/avatar"文件夹里)实现效果预览:二、解决方案1、插件的选择∙jQuery:这个是必备的一个插件可以到官网上下载/Downloading_jQuery∙imgAreSselect:这个是实现客户端上图片区域选择的/projects/imgareaselect/∙uploadify:实现文件的上传的功能,支持多文件上传,且可定制性非常强。
/download/上面的插件是用在客户端上,其实在我这个程序里写PHP时也用了一些插件。
其实我之所以写"图像剪裁上传"的起源是因为我看了《PHP快速开发工具箱》想自己练习一下的。
该书是有一个网址(/),里面有整本书的代码,而且每个插件都相应的demo,非常不错。
下面是用到的PHP插件:∙PIPHP_UploadFile.php:这是一个文件上传功能的php文件/plug-in11.php∙PIPHP_ImageCrop.php:这个php文件是具有对图片进行裁剪的功能/plug-in15.php2、客户端与服务器之间的交互图为了便于理解,我先把交互图放在这里。
其中绿色部分是客户端的主要步骤、粉红色是服务器端的主要步骤,服务器与客户端之间的交互通过AJAX完成。
可以发现,大部分的操作在客户端进行,服务器端与客户端之间的交流只是简单的JSON数据,因此这样给用户的体验是非常高的。
截图 1 客户端与服务器之间交互图3、客户端文件展示给用户的是html页面,为了学习并巩固CSS知识,就和DIV+CSS搭建了下面这样一个前台页面,见截图 2。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
在网上搜索了一下,发现以jquery+ajax方式实现单张图片上传的代码是有的,但实现批量上传图片的程序却没搜索到,于是根据搜索到的代码,写了一个可以批量上传的。
先看效果图点击增加按钮,会增加一个选择框,如下图:选择要上传的图片,效果图如下:上传成功如下图:下面来看代码:前台html主要代码:<button id="SubUpload" class="ManagerButton"onClick="TSubmitUploadImageFile();return false;">确定上传</button> <button id="CancelUpload" class="ManagerButton" onClick="javascript:history.go(-1);">取消</button> <button id="AddUpload" class="ManagerButton"onClick="TAddFileUpload();return false;">增加</button><tr><td class="tdClass">图片1:</td><td class="tdClass"><input name="" size="60" id="uploadImg1" type="file" /><span id="uploadImgState1"></span></td></tr>因为用了JQuery,所以你完全可以把click事件放在js文件中“增加”按钮js代码:var TfileUploadNum=1; //记录图片选择框个数var Tnum=1; //ajax上传图片时索引function TAddFileUpload(){var idnum = TfileUploadNum+1;var str="<tr><td class=’tdClass’>图片"+idnum+":</td>";str += "<td class=’tdClass’><input name=’’ size=’60’id=’uploadImg"+idnum+"’ type=’file’ /><spanid=’uploadImgState"+idnum+"’>";str += "</span></td></tr>";("#imgTable").append(str);TfileUploadNum += 1;}“确定上传”按钮js代码:function TSubmitUploadImageFile(){M("SubUpload").disabled=true;M("CancelUpload").disabled=true;M("AddUpload").disabled=true;setTimeout("TajaxFileUpload()",1000);//此为关键代码}关于setTimeout("TajaxFileUpload()",1000);这句代码:因为所谓的批量上传,其实还是一个一个的上传,给用户的只是一个假象。
只所以要延时执行TajaxFileUpload(),是因为在把图片上传到服务器上时,我在后台给图片重新命名了,命名的规则是,如下代码:Random rd = new Random();StringBuilder serial = new StringBuilder();serial.Append(DateTime.Now.ToString("yyyyMMddHHmmssff"));serial.Append(rd.Next(0, 999999).ToString());return serial.ToString();即使我命名精确到毫秒,另外再加上随机数,可是还是有上传的第二张图片把上传的第一张图片覆盖的情况出现。
所以此处我设置了延时1秒后在上传下一张图片。
刚开始做这个东西的时候,用的是for循环,来把所有的图片一个一个的循环地用ajax上传,可是for循环速度太快了,可能第一张图片还没来得及ajax,第二张就被for过来了,还是有第二张覆盖第一张的情况出现。
下面来看TajaxFileUpload()函数,代码如下:function TajaxFileUpload(){if(Tnum<TfileUploadNum+1)//准备提交处理("#uploadImgState"+Tnum).html("<img src=../images/loading.gif />");//开始提交.ajax({type: "POST",url:"http://localhost/ajaxText2/Handler1.ashx",data:{upfile:("#uploadImg"+Tnum).val(),category:("#pcategory").val()}, success:function (data, status){//alert(data);var stringArray = data.split("|");if(stringArray[0]=="1"){//stringArray[0] 成功状态(1为成功,0为失败)//stringArray[1] 上传成功的文件名//stringArray[2] 消息提示("#uploadImgState"+Tnum).html("<img src=../images/note_ok.gif />");//+stringArray[1]+"|"+stringArray[2]);}else{//上传出错("#uploadImgState"+Tnum).html("<img src=../images/note_error.gif />"+stringArray[2]);//+stringArray[2]+"");}Tnum++;setTimeout("TSubmitUploadImageFile()",0);}});}}上面的代码没什么可说的,很容易看懂。
下面来看Handler1.ashx(一般处理程序)如何来处理post过来的图片的(此代码来自网上,具体地址忘记了),下面只给出关键代码,全部代码在附件里。
string _fileNamePath = "";try{_fileNamePath = context.Request.Form["upfile"];//开始上传string _savedFileResult = UpLoadFile(_fileNamePath);context.Response.Write(_savedFileResult);}catch{context.Response.Write("0|error|上传提交出错");}2、//生成将要保存的随机文件名string fileName = GetFileName() + fileNameExt;//物理完整路径string toFileFullPath = HttpContext.Current.Server.MapPath(toFilePath); //检查是否有该路径没有就创建if (!Directory.Exists(toFileFullPath)){Directory.CreateDirectory(toFileFullPath);}///创建WebClient实例WebClient myWebClient = new WebClient();//设定windows网络安全认证方法1myWebClient.Credentials = CredentialCache.DefaultCredentials;//要上传的文件FileStream fs = new FileStream(fileNamePath, FileMode.Open, FileAccess.Read);//FileStream fs = OpenFile();BinaryReader r = new BinaryReader(fs);//使用UploadFile方法可以用下面的格式//myWebClient.UploadFile(toFile, "PUT",fileNamePath);byte[] postArray = r.ReadBytes((int)fs.Length);Stream postStream = myWebClient.OpenWrite(toFile, "PUT");if (postStream.CanWrite){postStream.Write(postArray, 0, postArray.Length);}3、检查是否合法的上传文件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;}4、生成要保存的随即文件名public static string GetFileName(){Random rd = new Random();StringBuilder serial = new StringBuilder();serial.Append(DateTime.Now.ToString("yyyyMMddHHmmssff"));serial.Append(rd.Next(0, 999999).ToString());return serial.ToString();}Ok,基本上这个批量上传图片的JQuery+ajax方式实现的程序完成了。