java图片上传并预览,前台用jQuery插件AjaxFileUpload,后台用FileUtils.copyFile.

合集下载

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();}};})();更多精彩内容请参考专题,和进⾏学习。

jQueryFileUpload文件上传插件使用详解

jQueryFileUpload文件上传插件使用详解

jQueryFileUpload⽂件上传插件使⽤详解 jQuery File Upload 是⼀个Jquery⽂件上传组件,⽀持多⽂件上传、取消、删除,上传前缩略图预览、列表显⽰图⽚⼤⼩,⽀持上传进度条显⽰;⽀持各种动态语⾔开发的服务器端。

特点:拖放⽀持;上传进度条;图像预览;可定制和可扩展的;兼容任何服务器端应⽤平台(PHP, Python, Ruby on Rails, Java, Node.js, Go etc.)。

使⽤⽅法:1. 需要加载的js⽂件:jquey-1.8.3.min.jsjquery-ui-widget.jsjquery.iframe-transport.jsjquery.fileupload.js2. html代码:<input id="fileupload" type="file" name="files[]" data-url="server/php/" multiple>3. js代码:$(function () {$('#fileupload').fileupload({dataType: 'json',done: function (e, data) {$.each(data.result.files, function (index, file) {$('<p/>').text().appendTo(document.body);});}});}); 3.1 显⽰上传进度条:  $('#fileupload').fileupload({ progressall: function (e, data) { var progress = parseInt(data.loaded / data.total * 100, 10); $('#progress .bar').css( 'width', progress + '%' ); } }); 3.2 需要⼀个<div>容器⽤来显⽰进: <div id="progress"> <div class="bar" style="width: 0%;"></div> </div>4. API4.1 Initialization:在上传按钮上调⽤fileupload()⽅法;⽰例:$('#fileupload').fileupload();4.2 Options :1: url:请求发送的⽬标urlType: stringExample: '/path/to/upload/handler.json'2.Type: ⽂件上传HTTP请求⽅式,可以选择“POST”,“PUT”或者"PATCH",默认"POST"Type: stringExample: 'PUT'3. dataType:希望从服务器返回的数据类型,默认"json"Type: stringExample: 'json'4. autoUpload:默认情况下,只要⽤户点击了开始按钮被添加⾄组件的⽂件会⽴即上传。

java中图片上传+预览+剪切解决方案

java中图片上传+预览+剪切解决方案

java中图片上传+预览+剪切解决方案我们在很多网站可以看到上传图片后可以剪切,下面我来介绍一个java中图片上传+预览+剪切解决方案吧,有需要的朋友可参考参考。

表现流程如下:步骤1:点击浏览按钮选中图片-------1------>onchange事件把图片上传到服务器-------2----->图片路径回传步骤2:进入切割图片------3----->切割,取得坐标,长度--------4---->传给服务器---------->后台切割产生新图片-----5------>回传新图路径步骤3:页面截图预览步骤1:file标签:onchange事件调用的js方法:ajaxFileUpload利用iframe模拟了ajax上传文件。

url:"uploadPreviewImage.html" 就是后台地址,(本人使用的是spring mvc),success:function (data , status),上传成功后调用的js中,$('#photo').imgAreaSelect方法是使用了imgAreaSelect插件来初始化截图界面。

官网地址:/projects/imgareaselect/关于ajaxFileUpload的api可以查看官网,开始的时候我使用的是网上随便下的一个js,发现一直调不同,最后换了官网的,才ok。

var f=document.getElementById("advImage").value;if(!/.(gif|jpg|jpeg|png|JPG|PNG)$/.test(f)){alert("图片类型必须是.jpeg,jpg,png中的一种")return false;}// 利用ajaxFileUpload js 插件上传图片$.ajaxFileUpload({url:"uploadPreviewImage.html",secureuri:false,fileElementId:"advImage",dataType:"json",success:function (data , status) {//上传成功后,直接跳出截图框,使用imgAreaSelect插件piso = $('#photo').imgAreaSelect({x1: 0, y1: 0, x2:480 , y2: 520 ,onSelectEnd: preview,resizable: false,instance: true,persistent:true});// 这个方法是现实一个div,托住截图框showCutImage();// 一些变量在页面的隐藏input的设置document.getElementById("photo").src = data.tempPath;document.getElementById("currentPath").valu e = data.tempPath;},error:function (data, status, e) {//alert("图片上传失败,请重新选择图片");}});return false;}// 截图选中后调用方法,保存好起始坐标和宽高function preview(img, selection){$('#x1').val(selection.x1);$('#y1').val(selection.y1);$('#x2').val(selection.x2);$('#y2').val(selection.y2);$('#w').val(selection.width);$('#h').val(selection.height);} uploadPreviewImage方法,把文件方法零时文件夹下:public ModelAndView uploadPreviewImage(HttpServletRequest request, HttpServletResponse response) throws IOException{User user = (User)request.getSession().getAttribute("user");MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest)request;MultipartFile image = multipartRequest.getFile("advImage");response.setCharacterEncoding(BusinessConstants.ENC OD_UTF);response.setHeader("ContentType", "json");PrintWriter out = response.getWriter();// 组合零时图片名String imageName = image.getOriginalFilename();String file_ext = imageName.substring(stIndexOf(BusinessConstants.DOT) + 1);SimpleDateFormat df = new SimpleDateFormat(BusinessConstants.DATE_FORMAT);String tempImageName = user.getId() +BusinessConstants.UNDERLINE + df.format(new Date()) + BusinessConstants.DOT + file_ext;// 存放浏览图片的零时文件路径File file = new File(request.getSession().getServletContext().getRealPath(Business Constants.TEMP_PICTURE_PATH +tempImageName));byte[] advImageBytes = null;InputStream advImageStream = null;try {file.createNewFile();advImageStream = image.getInputStream();advImageBytes = FileCopyUtils.copyToByteArray(advImageStream);FileCopyUtils.copy(advImageBytes, file);advImageStream.close();} catch (IOException e) {e.printStackTrace();}String tempPath = BusinessConstants.TEMP_RELATIVE_PICTURE_PATH +tempImageName;// 传给页面相对路径out.print("{");out.print("tempPath:'"+tempPath+"',");out.print("msg:''");out.print("}");out.flush();out.close();// ajaxreturn null;}上面的uploadPreviewImage调用完成后就会把下面的div显示出来(初始隐藏):这就是截图界面啦!<input id="h" type="hidden" /></div><input type="button" id="cutImage" name="cutImage" class="btton-queren" onclick="cutImage()" style="float: right;" value="保存"/></div>步骤2:我们可以看到截图完毕后点击保存,就会调用cutImage方法:里面我们利用dwr调用ReleaseService的cutImage方法。

javascriptinput图片上传及预览,FileReader预览图片

javascriptinput图片上传及预览,FileReader预览图片

javascriptinput图⽚上传及预览,FileReader预览图⽚FileReader是前端进⾏⽂件处理的⼀个重要的Api,特别是在对图⽚的处理上,如果你想知道图⽚的处理原理,你就永远不可能绕过它。

<!DOCTYPE html><html><head><meta charset="utf-8"><title></title><style type="text/css">.file-ipt{position: absolute;left:0;top: 0;opacity: 0;width: 50px;height: 25px;} //这⾥透明化了input框,然后绝对定位在按钮上了.btn{width: 50px;height: 25px; background-color: skyblue;color: white;margin-right: 80px;border: none;border-radius: 10px;font-size: 8px;}</style></head><body><button class="btn">图⽚</button><input type="file" id="file" accept="image/jpg,imgae/jpeg,image/png" class="file-ipt" onchange="insertimg(this);"><br><img src="" id="img1" alt=""><script language="javascript">function insertimg(img){var rd=new FileReader();files=img.files[0];var filetype=files.type.slice(6,10);if(filetype!='jpg'&&filetype!='jpeg'&&filetype!='png'){alert('仅⽀持png,jpeg,jpg图⽚格式');return;}else{rd.readAsDataURL(files);rd.onloadend=function(e){document.getElementById('img1').src=e.target.result;document.getElementById('img1').style.width="300px";document.getElementById('img1').style.height="auto";};}}</script></body></html>知识点补充:JS input file图⽚上传预览效果⾸先,可以先了解file 和FileReader 的API,在选取⼀个或者多个⽂件之后,访问到代表了所选⽂件的⼀个或多个File对象,这些对象被包含在⼀个FileList对象中。

jquery异步上传图片

jquery异步上传图片

jquery异步上传图⽚⽤ajaxfileupload.js插件实现图⽚的异步上传html代码<input id="img" type="file" name="img" />Js代码$('#img').change(function () {$.ajaxFileUpload({url:'demo.php', //你处理上传⽂件的服务端secureuri:false,fileElementId:'img',//与页⾯处理代码中file相对应的ID值 processData : false, contentType : false, dataType: 'text', //返回数据类型:看后端返回的是什么数据,在IE下后端要设置请求头的Content-Type:text/html; charset=UTF-8 success: function (data, status) {},error: function(data, status, e){ //提交失败⾃动执⾏的处理函数alert(e);}})});//可以添加⽂件后缀判断php代码<?php$path = "./";$extArr = array("jpg", "png", "gif");if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST"){$name = $_FILES['img']['name'];$size = $_FILES['img']['size'];if(empty($name)){echo '请选择要上传的图⽚';exit;}$ext = extend($name);if(!in_array($ext,$extArr)){echo '图⽚格式错误!';exit;}if($size>(100*1024)){echo '图⽚⼤⼩不能超过100KB';exit;}$image_name = time().rand(100,999).".".$ext;$tmp = $_FILES['img']['tmp_name'];if(move_uploaded_file($tmp, $path.$image_name)){echo '<img src="'.$path.$image_name.'" class="preview">';}else{echo '上传出错了!';}exit;}//获取⽂件类型后缀function extend($file_name){$extend = pathinfo($file_name);$extend = strtolower($extend["extension"]);return $extend;}参考博客:。

Ajax+PHP+jQuery图片截图上传

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。

JAVA jsp任意浏览器的图片上传预览

JAVA jsp任意浏览器的图片上传预览
success = false;
} success = true; // 如果用的是 struct2 那么 下面 就可以省了,直接 写一个 json 格式 返 回 ,在 页面 json 接收 就好了 比这个 省事!
Document document = DocumentHelper.createDocument(); Element result = document.addElement("Result"); Element succ = result.addElement("Success"); Element fileN = result.addElement("FileName"); succ.addText(success.toString()); fileN.addText(fileName); StringWriter stringWriter = new StringWriter();
开始做的满足了firefox35可是36不行40不行还要判断ie后来改到firefox353640ie都适应了可是最后用户用来safari浏览器又要改safarioperachrome这样的浏览非要后台才能支持的所以只要通过选择图片的时候来个异步上传写到服务器的一个临时目录下返回图片路径显示在img标签里面这个过程也是非常快的就跟本地预览一样的效果没有半点延迟的效果除非你的服务器配置和网络非常差
1.做对任意浏览器的本地预览的功能是不可能实现的 光是适应 IE 与 firefox 两个 浏览 器 就是 不太可能的,IE 6 与 IE 7 8 不同,IE 9 又
是一个样,firefox 3.5 与 3.6 还有 4.0 往上走的版本都不一样。 开始做的 满足了 firefox3.5 ,可是 3.6 不行,4.0 不行,还要判断 IE,后来 改到 适

AjaxFileUpload文件上传

AjaxFileUpload文件上传

AjaxFileUpload文件上传组件(php+jQuery+ajax)jQuery插件AjaxFileUpload可以实现ajax文件上传,下载地址:/contents/ajaxfileupload/ajaxfileupload.js主要参数说明:1、url表示处理文件上传操作的文件路径,可以测试URL是否能在浏览器中直接访问,如上:upload.php2、fileElementId表示文件域ID,如上:fileToUpload3、secureuri是否启用安全提交,默认为false4、dataType数据数据,一般选json,javascript的原生态5、success提交成功后处理函数6、error提交失败处理函数需要了解相关的错误提示1、SyntaxError: missing ; before statement错误如果出现这个错误就需要检查url路径是否可以访问2、SyntaxError: syntax error错误如果出现这个错误就需要检查处理提交操作的PHP文件是否存在语法错误3、SyntaxError: invalid property id错误如果出现这个错误就需要检查属性ID是否存在4、SyntaxError: missing } in XML expression错误如果出现这个错误就需要检查文件域名称是否一致或不存在5、其它自定义错误大家可使用变量$error直接打印的方法检查各参数是否正确,比起上面这些无效的错误提示还是方便很多。

示例代码:Upload.html<!doctype html><html><head><!-- <meta charset="UTF-8">--><title>ajaxfileupload图片上传控件</title><script src="/jquery-1.6.3.min.js"></script><script src="js/ajaxfileupload.js"></script></head><body><input type="file" size="20" name="fileToUpload" class="input" id="fileToUpload"><button id="buttonUpload">上传</button><script>$(function () {$('#buttonUpload').click(function () {$.ajaxFileUpload({url:'upload.php',//处理图片脚本secureuri :false,fileElementId :'fileToUpload',//file控件iddataType : 'json',success: function (data,status) {if(typeof (data.error) != 'undefined' ){if(data.error != ''){alert(data.error);}else{alert(data.msg);}}},error: function (data,status,e) {alert(e);}});return false;});});</script></body></html>Upload.php文件<?php/*** Created by PhpStorm.* User: Administrator* Date: 2015/8/7* Time: 11:15*/$res["error"] = "";//错误信息$res["msg"] = "";//提示信息if(move_uploaded_file($_FILES['fileToUpload']['tmp_name'],"c:\\qq.jpg ")){$res["msg"] = "ok";}else{$res["error"] = "error";}echo json_encode($res);?>jQuery HTMLjQuery—获取内容和属性jQuery DOM操作获得内容:text()、html()、以及val()三个简单的用于DOM操作的jQuery方法:。

Ajax实现图片上传并预览功能

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实现图⽚上传并预览功能,希望对⼤家有所帮助,如果⼤家有任何疑问请给我留⾔,⼩编会及时回复⼤家的。

$.ajaxfileupload用法

$.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,用于多文件上传。

javaweb使用ajax实现文件上传

javaweb使用ajax实现文件上传

javaweb使⽤ajax实现⽂件上传在javaweb中,使⽤ajax实现⽂件上传预览1.表单: -设置input type="file",multiple="multiple"可以选择多个⽂件,id是⽤来获取element,上⾯的hidden是⽤来保存字段值,即保存最终的⽂件名称,可能是多个2.js:<script type="text/javascript">var inputEle = document.getElementById('file1');inputEle.onchange = function (e) {var formData = new FormData();for (var i = 0; i < this.files.length; i++) {var file = this.files[i];console.log(file);formData.append('file', file);};formData.append('eId', ${dInfo.enterpriseId});// formData.append(其他参数)if(this.files.length > 0){ //有⽂件就call后台,没有就不callvar type="handleagreementattachment";var falg="fileFlag1";fileUpload(formData,type,falg);}}//⽂件上传,call后台function fileUpload(formData,type,flag) {$.ajax({url: "${ctx}/file/fileUtil/FileUpload",type: 'POST',cache: false,processData: false,contentType: false,enctype:"multipart/form-data",dataType:"json",data: formData,async:false,error: function (request) {alert("服务器故障");},success: function (data) {console.log(data); //wasterwatermonitorattachmentvar fileValue = $("#"+ type +"").val();for(var i=0;i<data.length;i++){fileValue += data[i]["fileName"]+";";//回显预览var radom = Math.random().toString(36).substring(2);$("#"+ flag +"").append("<li id='"+ radom +"'><a href='"+ data[i]["fileAdd"]+data[i]["fileName"] +"' style='width:60px;' title="+ data[i]["fileName"] +">" +"<img src='${ctxStatic}/hb/fileimages/"+ data[i]["type"] +".png' alt='' style='margin-bottom: 10px'/><b>"+ data[i]["shortName"] +"</b></a>" +"<b style='color:red;cursor:pointer;' onclick=delFile('"+ radom +"','"+ data[i]["fileName"] +"','"+ type +"');>删除</b></li>");}$("#"+ type +"").val(fileValue);}});}//删除⽂件function delFile(id,name,type) {var a = confirm("确认删除 " + name + " 吗?");if(a==true){var node = document.getElementById(id);node.remove(); //删除这个节点var value = $("#"+ type +"").val(); //获取本来的字段值value = value.replace(name+";",""); //删除其中的某个⽂件$("#"+ type +"").val(value); //重新赋值return true;}else{return false;}}</script> 要注意这⼀块script要放到<body>的最下⾯,否则会导致 inputEle 获取不到element,因为页⾯没有加载完成;ajax call的时候只需要传递formData 就可以了,我这边是业务需求所以多了⼏个对象。

jQuery实现图片上传预览效果功能完整实例【测试可用】

jQuery实现图片上传预览效果功能完整实例【测试可用】

jQuery实现图⽚上传预览效果功能完整实例【测试可⽤】本⽂实例讲述了jQuery实现图⽚上传预览效果功能。

分享给⼤家供⼤家参考,具体如下:<!DOCTYPE html><html><head><meta charset="utf-8" /><title> jquery图⽚上传预览效果</title><script src="/jquery/2.0.0/jquery.min.js"></script></head><body><input type="file" id="browsefile" ><div class="images_show" id="images_show"><p class="first">上传图⽚预览区</p><p>图⽚仅限JPG、PNG格式</p><p>⽂件尺⼨:532×400px</p><p>⽂件⼤⼩:200K以内</p></div></div><script type="text/javascript">//处理file input加载的图⽚⽂件$(document).ready(function(e) {//判断浏览器是否有FileReader接⼝if(typeof FileReader =='undefined'){/*$("#images_show").css({'background':'none'}).html('亲,您的浏览器还不⽀持HTML5的FileReader接⼝,⽆法使⽤图⽚本地预览,请更新浏览器获得最好体验');*/ //如果浏览器是ieif($.browser.msie===true){//ie6直接⽤file input的value值本地预览if($.browser.version==6){$("#browsefile").change(function(event){//ie6下怎么做图⽚格式判断?var src = event.target.value;//var src = document.selection.createRange().text; //选中后 selection对象就产⽣了这个对象只适合ievar img = '<img src="'+src+'" width="200px" height="200px" />';$("#images_show").empty().append(img);});}//ie7,8使⽤滤镜本地预览else if($.browser.version==7 || $.browser.version==8){$("#browsefile").change(function(event){$(event.target).select();var src = document.selection.createRange().text;var dom = document.getElementById('images_show');console.log(src);//使⽤滤镜成功率⾼$("#images_show").css({"filter":"progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)"});/*dom.filters.item('DXImageTransform.Microsoft.AlphaImageLoader').src= src;*/dom.innerHTML = '<img id="head" alt=" " src=+src+ />';//使⽤和ie6相同的⽅式设置src为绝对路径的⽅式有些图⽚⽆法显⽰效果没有使⽤滤镜好/*var img = '<img src="'+src+'" width="200px" height="200px" />';$("#images_show").empty().append(img);*/});}}//如果是不⽀持FileReader接⼝的低版本firefox 可以⽤getAsDataURL接⼝else if($.browser.mozilla===true){$("#browsefile").change(function(event){//firefox2.0没有event.target.files这个属性就像ie6那样使⽤value值但是firefox2.0不⽀持绝对路径嵌⼊图⽚放弃firefox2.0//firefox3.0开始具备event.target.files这个属性并且开始⽀持getAsDataURL()这个接⼝⼀直到firefox7.0结束不过以后都可以⽤HTML5的FileReader接⼝了 if(event.target.files){//console.log(event.target.files);for(var i=0;i<event.target.files.length;i++){var img = '<img src="'+event.target.files.item(i).getAsDataURL()+'" width="200px" height="200px"/>';$("#images_show").empty().append(img);}}else{//console.log(event.target.value);//$("#imgPreview").attr({'src':event.target.value});}});}}else{// version 1/*$("#imgUpload").change(function(e){var file = e.target.files[0];var fReader = new FileReader();//console.log(fReader);//console.log(file);fReader.onload=(function(var_file){return function(e){$("#imgPreview").attr({'src':e.target.result,'alt':var_});}})(file);fReader.readAsDataURL(file);});*///单图上传 version 2/*$("#imgUpload").change(function(e){var file = e.target.files[0];var reader = new FileReader();reader.onload = function(e){//displayImage($('bd'),e.target.result);//alert('load');$("#imgPreview").attr({'src':e.target.result});}reader.readAsDataURL(file);});*///多图上传 input file控件⾥指定multiple属性 e.target是dom类型$("#browsefile").change(function(e){for(var i=0;i<e.target.files.length;i++){var file = e.target.files.item(i);//允许⽂件MIME类型也可以在input标签中指定accept属性//console.log(/^image\/.*$/i.test(file.type));if(!(/^image\/.*$/i.test(file.type))){continue; //不是图⽚就跳出这⼀次循环}//实例化FileReader APIvar freader = new FileReader();freader.readAsDataURL(file);freader.onload=function(e){var img = '<img src="'+e.target.result+'" width="200px" height="200px"/>';$("#images_show").empty().append(img);}}});//处理图⽚拖拽的代码var destDom = document.getElementById('images_show');destDom.addEventListener('dragover',function(event){event.stopPropagation();event.preventDefault();},false);destDom.addEventListener('drop',function(event){event.stopPropagation();event.preventDefault();var img_file = event.dataTransfer.files.item(0); //获取拖拽过来的⽂件信息暂时取⼀个//console.log(event.dataTransfer.files.item(0).type);if(!(/^image\/.*$/.test(img_file.type))){alert('您还未拖拽任何图⽚过来,或者您拖拽的不是图⽚⽂件');return false;}fReader = new FileReader();fReader.readAsDataURL(img_file);fReader.onload = function(event){destDom.innerHTML='';destDom.innerHTML = '<img src="'+event.target.result+'" width="200px" height="200px"/>'; };},false);}});</script></body></html>更多关于jQuery相关内容感兴趣的读者可查看本站专题:《》、《》、《》、《》、《》、《》及《》希望本⽂所述对⼤家jQuery程序设计有所帮助。

preview图片预览(异步上传)

preview图片预览(异步上传)
$("#showImage").html("<img src='<%=ctx%>/upload/photo/"+data[1]+"' height='100' width='200'/>");
return false;
<div id="message"></div>
<div id="showImage" ></div>
</form>
<s:file name="photo" id="photo" theme="simple" cssClass="inpbox" cssStyle="width:300"></s:file>
<input type="button" onclick="upload()" value="上传图像"/>
} else {
var data = msg.split("'");
$("#message").html("<font color='red'>"+ data[1]+"</font>");//在相应的位置显示信息
ajax异步上传文件(图片预览)
jsp:(注意enctype属性)
引用jquery.form.js

jQuery插件AjaxFileUpload可以实现文件上传

jQuery插件AjaxFileUpload可以实现文件上传

jQuery插件AjaxFileUpload可以实现ajax文件上传,该插件使用非常简单,首先了解一下正确使用AjaxFileUpload插件的方法,然后再了解一些常见的错误信息和解决方法。

使用说明需要使用jQuery库文件和AjaxFileUpload库文件使用实例一,包含文件部分复制代码代码如下:<script type="text/javascript" src="jquery.js"></script><script type="text/javascript" src="ajaxfileupload.js"></script>二,HTML部分复制代码代码如下:<img id="loading " src="loading.gif" style="display:none;"><input id="fileToUpload " type="file" size="20" name="fileToUpload " class="input"> <button class="button" id="buttonUpload" onclick="return ajaxFileUpload ();">上传</button>只需要三个元素,一个动态加载小图标、一个文件域和一个按钮注意:使用AjaxFileUpload插件上传文件可不需要form,如下:<form name="form" action="" method="POST" enctype="multipart/form-data"> ……相关html代码……</form>因为AjaxFileUpload插件会自动生成一个form提交表单。

JQuery+ajax实现批量上传图片

JQuery+ajax实现批量上传图片

在网上搜索了一下,发现以jquery+ajax方式实现单张图片上传的代码是有的,但实现批量上传图片的程序却没搜索到,于是根据搜索到的代码,写了一个可以批量上传的。

先看效果图点击增加按钮,会增加一个选择框,如下图:选择要上传的图片,效果图如下:上传成功如下图:下面来看代码:前台html主要代码:<button id="SubUpload" class="ManagerButton"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><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);这句代码:因为所谓的批量上传,其实还是一个一个的上传,给用户的只是一个假象。

jquery实现图片上传前本地预览功能

jquery实现图片上传前本地预览功能

jquery实现图⽚上传前本地预览功能本⽂实例为⼤家分享了jquery实现图⽚上传前预览的具体代码,供⼤家参考,具体内容如下介绍之前有⼀个⼩问题,⼀直找不到图⽚预览时,图⽚不出来的原因,原来在于图⽚的路径⼀直写的是图⽚的本地路径,没有什么⽤。

直接上代码。

html部分:复制代码代码如下:<img id="pic" src="" ><input id="upload" name="file" accept="image/*" type="file" style="display: none"/>input:file事件是上传类型较常⽤的属性值如下:accept:表⽰可以选择的⽂件MIME类型,多个MIME类型⽤英⽂逗号分开,常⽤的MIME类型见下表。

若要⽀持所有图⽚格式,则写 * 即可。

multiple:是否可以选择多个⽂件,多个⽂件时其value值为第⼀个⽂件的虚拟路径input:file的样式是不变的,所以若要改变它的样式,⾸先将它隐藏。

display:none;CSS部分:因为做的是⼀个圆形的头像,所以对图⽚样式先进⾏定义。

#pic{width:100px;height:100px;border-radius:50% ;margin:20px auto;cursor: pointer;}jQuery部分:$(function() {$("#pic").click(function () {$("#upload").click(); //隐藏了input:file样式后,点击头像就可以本地上传$("#upload").on("change",function(){var objUrl = getObjectURL(this.files[0]) ; //获取图⽚的路径,该路径不是图⽚在本地的路径if (objUrl) {$("#pic").attr("src", objUrl) ; //将图⽚路径存⼊src中,显⽰出图⽚}});});});//建⽴⼀個可存取到該file的urlfunction getObjectURL(file) {var url = null ;if (window.createObjectURL!=undefined) { // basicurl = window.createObjectURL(file) ;} else if (window.URL!=undefined) { // mozilla(firefox)url = window.URL.createObjectURL(file) ;} else if (window.webkitURL!=undefined) { // webkit or chromeurl = window.webkitURL.createObjectURL(file) ;}return url ;}运⾏结果如下:更多精彩内容,请点击,进⾏深⼊学习和研究。

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

本文由我司收集整编,推荐下载,如有疑问,请与我司联系java 图片上传并预览,前台用jQuery 插件AjaxFileUpload,后台用
FileUtils.copyFile.
2015/01/05 0 个人笔记,以备后用.
表体代码:
td colspan= 3 s:file label= 上传name= uploadFile id= uploadNumFile onchange= fileUpload( uploadNumFile , goodsRecordDtl_goodsPicture , goodsPicture_img ) / a href= # title= 查看quot;viewPic( viewPicture1 , goodsPicture , goodsRecordDtl_goodsPicture 查看图片/a div id= viewPicture1 title= 图片预览> img id= goodsPicture src= /div /td
js 代码(记得要引入jquery 库和ajaxfileupload 库):
//上传文件id 号function fileUpload(uploadFileId,filePathId,imgId){ var imp= document.getElementById(uploadFileId); if(imp==null ||imp== ||imp== undefined){ alert( 请选择文件return; } $.ajaxFileUpload({ url:ct + uploadFile.do , secureuri:false, fileElementId:uploadFileId, dataType: multipart/form-data , success: function (data, status){ var json = eval( ( + data + ) if(json.msg== 1 ){ alert( 上传成功$( # +filePathId).val(json.path); $( # +imgId).attr( src ,eTrade.ctx+ /upload/ +json.path); }else{ alert( 文件上传失败} }, error: function (data, status, e){ alert(e); } }); } function viewPic(dialogId,imgId,fileId){ $( # +dialogId).dialog({ height: 350, width: 600, buttons: { 取消: function() { $( # +imgId).attr( src , $(this).dialog( close } }, close:function(){ $( # +imgId).attr( src , } }); if($( # +fileId).val()== ){ return; } $( # +imgId).attr(
src ,ct+ /toView.do?attachment= +$( # +fileId).val()); }
后台代码(uploadFile 命名必须与前台name= uploadFile 一致):
private File uploadFile; public File getUploadFile() { return uploadFile; } public void setUploadFile(File uploadFile) { this.uploadFile = uploadFile; } @Action(value = uploadFile , results = { @Result(name = success , type = json , params = { ignoreHierarchy , false , contentType , text/html , root , dataMap }) }) public String。

相关文档
最新文档