JQuery+ajax实现批量上传图片

合集下载

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

通过ajax、servlet实现图片的上传功能

通过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⾏并⾮是读取⽂件的真正内容, * 从第四⾏开始才是正⽂数据。

WEB页面通过ajax进行图片上传实例(附代码)

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上传

上传概述上传类使用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>复制代码上面的表单,在保存用户数据的同时包括了一个照片文件上传,使用普通方式提交到后台后,系统自动会把用户数据保存在用户数据表中,而把上传的文件保存到附件数据表,并记录了对应的用户数据表的名称和编号。

php+ajax+h5实现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'];}。

PHP+jQuery+Ajax仿淘宝多上传按钮单文件上传

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+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。

jQuery多图上传插件imgUp.js

jQuery多图上传插件imgUp.js

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

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

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' /><span id='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("<imgsrc=../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过来的图片的(此代码来自网上,具体地址忘记了),下面只给出关键代码,全部代码在附件里。

1、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方式实现的程序完成了。

相关文档
最新文档