菜单

上传图片

2020年3月8日 - 首页

本文实例陈说了jquery插件ajaxupload完结公文上传操作代码。分享给大家供我们参谋。具体如下:运营作效果果截图如下:

 来源:

1、创造页面并编辑HTML

本次使用AJAXUPLOAD做为上传顾客端无刷上传插件,其新式版本为3.9,官方地址:

2、引用AjaxUpload.js文件

在页面中引进 jquery.min.1.4.2.js 和 ajaxupload.js

3、编写JS脚本

<script src="Scripts/jquery-1.4.2.min.js" type="text/javascript"></script>
<script src="Scripts/ajaxupload3.9.js" type="text/javascript"></script>
window.onload = function; //初始化 } //初始化 function init() { //初始化文档上传 var btnFile = document.getElementById; var doc = document.getElementById; var hidFileName = document.getElementById; document.getElementById.onclick = function() { DelFile; }; g_AjxUploadFile(btnFile, doc, hidFileName); //初始化图片上传 var btnImg = document.getElementById; var img = document.getElementById; var hidImgName = document.getElementById; document.getElementById.onclick = function() { DelImg; }; 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 { if (!(ext && /^(rar|zip|pdf|pdfx|txt|csv|xls|xlsx|doc|docx|RAR|ZIP|PDF|PDFX|TXT|CSV|XLS|XLSX|DOC|DOCX)$/.test { alert; return false; } }, onComplete: function { flagValue = response; if  { alert; } else if  { alert; } else if  { alert; } else { hidPut.value = response; doc.innerHTML="" + response + ""; } } }); } //图片上传 function g_AjxUploadImg { var button = btn, interval; new AjaxUpload(button, { action: '/Common/UploadHandler.ashx?fileType=img', data: {}, name: 'myfile', onSubmit: function { if (!(ext && /^(jpg|JPG|png|PNG|gif|GIF)$/.test { alert; return false; } }, onComplete: function { flagValue = response; if  { alert; } else if  { alert("您上传的图片大于200K,请重新选择!"); } else if  { alert; } else { hidPut.value = response; img.src = g_AjxTempDir + response; } } }); } //删除文档 function DelFile { hidPut.value = ""; doc.innerHTML = ""; } //删除图片 function DelImg { hidPut.value = ""; img.src = "https://www.jb51.net/images/nophoto.gif"; } 

HTML 代码:

4、成立/Common/UploadHandler.ashx管理程序

<style type="text/css">
        #txtFileName {
            width: 300px;
        }
        .btnsubmit{border-bottom: #cc4f00 1px solid; border-left: #ff9000 1px solid;border-top: #ff9000 1px solid;   border-right: #cc4f00 1px solid;text-align: center; padding: 2px 10px; line-height: 16px; background: #e36b0f;  height: 24px; color: #fff; font-size: 12px; cursor: pointer;}
    </style>

上传图片:<input type="text" id="txtFileName" /><div  id="btnUp" style="width:300px;" class=btnsubmit >浏览</div>
<div id="imglist"></div>
 using System; using System.Web; using System.Text.RegularExpressions; using System.IO; public class UploadHandler : IHttpHandler { private string _filedir = ""; //文件目录 ///  /// 处理上传文件(1:文件格式不正确、2:文件大小不正确、3:上传失败、文件名称:上传成功) ///  ///  public void ProcessRequest  { _filedir = context.Server.MapPath; try { string result = "3"; string fileType = context.Request.QueryString["fileType"]; //获取上传文件类型 if  { result = UploadFile; //文档上传 } else if  { result = UploadImg; //图片上传 } context.Response.Write; } catch { context.Response.Write;//3文件上传失败 } } ///  /// 文档上传 ///  ///  ///  private string UploadFile { int cout = context.Request.Files.Count; if  { HttpPostedFile hpf = context.Request.Files[0]; if  { string fileExt = Path.GetExtension.ToLower(); //只能上传文件,过滤不可上传的文件类型 string fileFilt = ".rar|.zip|.pdf|.pdfx|.txt|.csv|.xls|.xlsx|.doc|.docx......"; if (fileFilt.IndexOf { return "1"; } //判断文件大小 int length = hpf.ContentLength; if  { 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 + Path.GetExtension; if (!Directory.Exists { Directory.CreateDirectory; } string fileName = _filedir + newFileName; hpf.SaveAs; return newFileName; } } return "3"; } ///  /// 图片上传 ///  ///  ///  private string UploadImg { int cout = context.Request.Files.Count; if  { HttpPostedFile hpf = context.Request.Files[0]; if  { string fileExt = Path.GetExtension.ToLower(); //只能上传文件,过滤不可上传的文件类型 string fileFilt = ".gif|.jpg|.php|.jsp|.jpeg|.png|......"; if (fileFilt.IndexOf { return "1"; } //判断文件大小 int length = hpf.ContentLength; if  { 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 + Path.GetExtension; if (!Directory.Exists { Directory.CreateDirectory; } string fileName = _filedir + newFileName; hpf.SaveAs; return newFileName; } } return "3"; } #region IHttpHandler 成员 public bool IsReusable { get { throw new NotImplementedException(); } } #endregion } 

 js代 码:

上传图片。附件1:页面CSS样式

<script type="text/javascript">

    $(function () {
        var button = $('#btnUp'), interval;
        new AjaxUpload(button, {
            //action: 'upload-test.php',文件上传服务器端执行的地址
            action: '/handler/AjaxuploadHandler.ashx',
            name: 'myfile',
            onSubmit: function (file, ext) {
                if (!(ext && /^(jpg|jpeg|JPG|JPEG)$/.test(ext))) {
                    alert('图片格式不正确,请选择 jpg 格式的文件!', '系统提示');
                    return false;
                }

                // change button text, when user selects file
                button.text('上传中');

                // If you want to allow uploading only 1 file at time,
                // you can disable upload button
                this.disable();

                // Uploding -> Uploading. -> Uploading...
                interval = window.setInterval(function () {
                    var text = button.text();
                    if (text.length < 10) {
                        button.text(text + '|');
                    } else {
                        button.text('上传中');
                    }
                }, 200);
            },
            onComplete: function (file, response) {
                //file 本地文件名称,response 服务器端传回的信息
                button.text('上传图片(只允许上传JPG格式的图片,大小不得大于150K)');

                window.clearInterval(interval);

                // enable upload button
                this.enable();

                var k = response.replace("<PRE>", "").replace("</PRE>", "");

                if (k == '-1') {
                    alert('您上传的文件太大啦!请不要超过150K');
                }
                else {
                    alert("服务器端传回的串:"+k);
                    alert("本地文件名称:"+file);
                    $("#txtFileName").val(k);
                    $("<img />").appendTo($('#imglist')).attr("src", k);
                }
            }
        });

    });
</script>
/*上传文件*/ .uploadFile{margin-bottom:10px;} /*上传图片*/ .uploadImg{} .uploadImg img{width:102px; height:64px; border:1px solid #CCCCCC; display: block;} 

劳务器端 ajaxuploadhandler.ashx 代码

附件2:AjaxUpload.js文件

public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";

            HttpPostedFile postedFile = context.Request.Files[0];
            string savePath = "/upload";
            int filelength = postedFile.ContentLength;
            int fileSize = 163600; //150K
            string fileName = "-1"; //返回的上传后的文件名
            if (filelength <= fileSize)
            {

                byte[] buffer = new byte[filelength];

                postedFile.InputStream.Read(buffer, 0, filelength);

                fileName = UploadImage(buffer, savePath, "jpg");

            }

            context.Response.Write(fileName);
        }

        public static string UploadImage(byte[] imgBuffer, string uploadpath, string ext)
        {
            try
            {
                System.IO.MemoryStream m = new MemoryStream(imgBuffer);

                if (!Directory.Exists(HttpContext.Current.Server.MapPath(uploadpath)))
                    Directory.CreateDirectory(HttpContext.Current.Server.MapPath(uploadpath));

                string imgname = CreateIDCode() + "." + ext;

                string _path = HttpContext.Current.Server.MapPath(uploadpath) + imgname;

                Image img = Image.FromStream(m);
                if (ext == "jpg")
                    img.Save(_path, System.Drawing.Imaging.ImageFormat.Jpeg);
                else
                    img.Save(_path, System.Drawing.Imaging.ImageFormat.Gif);
                m.Close();

                return uploadpath + imgname;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }

        }

        public static string CreateIDCode()
        {
            DateTime Time1 = DateTime.Now.ToUniversalTime();
            DateTime Time2 = Convert.ToDateTime("1970-01-01");
            TimeSpan span = Time1 - Time2;   //span就是两个日期之间的差额   
            string t = span.TotalMilliseconds.ToString("0");

            return t;
        }
/** * AJAX Upload ( http://valums.com/ajax-upload/ ) * Copyright  Andris Valums * Licensed under the MIT license ( http://valums.com/mit-license/ ) * Thanks to Gary Haran, David Mark, Corey Burns and others for contributions */  { /* 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  != 'undefined' && typeof == 'function') { Array.prototype.unshift.call(arguments, '[Ajax Upload]'); console.log(Array.prototype.join.call; } } /** * Attaches event to a dom element. * @param {Element} el * @param type event name * @param fn callback This refers to the passed element */ function addEvent { if  { el.addEventListener; } else if  { el.attachEvent('on' + type, function ; } 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 * http://www.quirksmode.org/dom/events/resize.html * * @param fn callback This refers to the passed element */ function addResizeEvent { var timeout; addEvent(window, 'resize', function  { clearTimeout; } timeout = setTimeout; } // Needs more testing, will be rewriten for next version // getOffset function copied from jQuery lib  if (document.documentElement.getBoundingClientRect) { // Get Offset using getBoundingClientRect // http://ejohn.org/blog/getboundingclientrect-is-awesome/ var getOffset = function  { var box = el.getBoundingClientRect(); var doc = el.ownerDocument; var body = doc.body; var docElem = doc.documentElement; // for ie var 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; } if  { 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 offsets var getOffset = function  { var top = 0, left = 0; do { top += el.offsetTop || 0; left += el.offsetLeft || 0; el = el.offsetParent; } while ; 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 { var left, right, top, bottom; var offset = getOffset; 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 { for  { if (styles.hasOwnProperty { 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 { var box = getBox; 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 =  { var div = document.createElement; return function  { div.innerHTML = html; var el = div.firstChild; return div.removeChild; /** * Function generates unique id * @return unique id */ var getUID =  { var id = 0; return function () { return 'ValumsAjaxUpload' + id++; }; })(); /** * Get file name from path * @param {String} file path to file * @return filename */ function fileFromPath { return file.replace; } /** * Get file extension lowercase * @param {String} file name * @return file extenstion */ function getExt { return (-1 !== file.indexOf ? file.replace : ''; } function hasClass { var re = new RegExp; return re.test; } function addClass { if  { el.className += ' ' + name; } } function removeClass { var re = new RegExp; el.className = el.className.replace; } function removeNode { el.parentNode.removeChild; } /** * 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  { this._settings = { // Location of the server-side upload script action: 'upload.php', // File upload name name: 'userfile', // Additional data to send data: {}, // Submit file as soon as it's selected autoSubmit: 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 hovered hoverClass: 'hover', // Class applied to button when AU is disabled disabledClass: 'disabled', // When user selects a file, useful with autoSubmit disabled // You can return false to cancel upload onChange: function  {}, // Callback to fire before file is uploaded // You can return false to cancel upload onSubmit: function  {}, // Fired when file upload is completed // WARNING! DO NOT USE "FALSE" STRING AS A RESPONSE! onComplete: function  {} }; // Merge the users options with our defaults for  { if (options.hasOwnProperty { this._settings[i] = options[i]; } } // button isn't necessary a dom element if  { // jQuery object was passed button = button[0]; } else if (typeof button == "string") { if  { // If jQuery user passes #elementId don't break it button = button.slice; } button = document.getElementById; } if (!button || button.nodeType !== 1) { throw new Error("Please make sure that you're passing a valid element"); } if (button.nodeName.toUpperCase { // disable link addEvent(button, 'click', function  { if (e && e.preventDefault) { e.preventDefault(); } else if  { window.event.returnValue = false; } }); } // DOM element this._button = button; // DOM element this._input = null; // If disabled clicking on button won't do anything this._disabled = false; // if the button was disabled before refresh if will remain // disabled in FireFox, let's fix it this.enable(); this._rerouteClicks(); }; // assigning methods to our class AjaxUpload.prototype = { setData: function  { 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 input if  { // 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 file this._input.parentNode.style.visibility = 'hidden'; } }, enable: function () { removeClass(this._button, this._settings.disabledClass); this._button.removeAttribute; this._disabled = false; }, /** * Creates invisible file input * that will hover above the button *  */ _createInput: function () { var self = this; var input = document.createElement; input.setAttribute; input.setAttribute('name', this._settings.name); 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; 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 filter if (div.style.opacity !== "0") { if  == 'undefined') { throw new Error('Opacity not supported by the browser'); } div.style.filter = "alpha"; } addEvent(input, 'change', function () { if (!input || input.value === '') { return; } // Get filename from input, required // as some browsers have path instead of it var file = fileFromPath; if (false === self._settings.onChange.call(self, file, getExt { self._clearInput(); return; } // Submit form when value is changed if (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 file input.parentNode.style.visibility = 'hidden'; }); div.appendChild; document.body.appendChild; this._input = input; }, _clearInput: function  { return; } // this._input.value = ''; Doesn't work in IE6 removeNode(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  { return; } if  { self._createInput(); } var div = self._input.parentNode; copyLayout; 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{ // if { // 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 :; // 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.setAttribute; var iframe = toElement(''); // src="javascript:false;%20was%20added%20//%20because%20it%20possibly%20removes%20ie6%20prompt%20//%20"This page contains both secure and nonsecure items" // Anyway, it doesn't do any harm. iframe.setAttribute; iframe.style.display = 'none'; document.body.appendChild; return iframe; }, /** * Creates form, that will be submitted to iframe * @param {Element} iframe Where to submit * @return {Element} form */ _createForm: function  { var settings = this._settings; // We can't use the following code in IE6 // var form = document.createElement; // form.setAttribute; // form.setAttribute('enctype', 'multipart/form-data'); // Because in this case file won't be attached to request var form = toElement; form.setAttribute('action', settings.action); form.setAttribute('target', iframe.name); form.style.display = 'none'; document.body.appendChild; // Create hidden input element for each data key for (var prop in settings.data) { if (settings.data.hasOwnProperty { var el = document.createElement; el.setAttribute; el.setAttribute; el.setAttribute('value', settings.data[prop]); form.appendChild; } } return form; }, /** * Gets response from iframe and fires onComplete event when ready * @param iframe * @param file Filename to use in onComplete callback */ _getResponse: function  { // getting response var toDeleteFlag = false, self = this, settings = this._settings; addEvent(iframe, 'load', function () { if ( // For Safari iframe.src == "javascript:'%3Chtml%3E%3C/html%3E';" || // For FF, IE iframe.src == "javascript:'';") { // First time around, do not delete. // We reload to blank page, so that reloading main page // does not re-submit the post. if  { // Fix busy state in FF3 setTimeout { removeNode; } return; } var doc = iframe.contentDocument ? iframe.contentDocument : window.frames[iframe.id].document; // fixing Opera 9.26,10.00 if (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 browsers return; } // fixing Opera 9.64 if (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 sec return; } var response; if  { // response is a xml document Internet Explorer property response = doc.XMLDocument; } else if  { // response is html document or plain text response = doc.body.innerHTML; if (settings.responseType && settings.responseType.toLowerCase { // If the document was sent as 'application/javascript' or // 'text/javascript', then the browser wraps the text in a  // 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/html if (doc.body.firstChild && doc.body.firstChild.nodeName.toUpperCase { response = doc.body.firstChild.firstChild.nodeValue; } if  { response = eval; } else { response = {}; } } } else { // response is a xml document response = doc; } settings.onComplete.call; // Reload blank page, so that reloading main page // does not re-submit the post. Also, remember to // delete the frame toDeleteFlag = true; // Fix IE mixed content issue iframe.src = "javascript:'';"; }); }, /** * Upload file contained in this._input */ submit: function () { var self = this, settings = this._settings; if (!this._input || this._input.value === '') { return; } var file = fileFromPath; // user returned false to cancel upload if (false === settings.onSubmit.call(this, file, getExt { this._clearInput(); return; } // sending request var iframe = this._createIframe(); var form = this._createForm; // assuming following structure // div -> input type='file' removeNode(this._input.parentNode); removeClass(self._button, self._settings.hoverClass); form.appendChild; form.submit(); // request set, clean up removeNode; form = null; removeNode; this._input = null; // Get response from iframe and fire onComplete event when ready this._getResponse; // get ready for next request this._createInput; 

.

越来越多赏心悦目内容请参见专项论题《ajax上传技术汇总》,《javascript文件上传操作汇总》和《jQuery上传操作汇总》举行学习。

.

上述正是ajaxupload达成公文上传操作的详实代码,希望对我们的上学抱有利于。

.

来源:

在PHP网站开拓中,文件上传功用时常使用,以前本身已介绍过何以接收PHP达成公文上传作用。随着WEB技能的升华,顾客体验成为衡量网址成功与否的根本,今日和大家享用什么在PHP中运用Jquery完成Ajax情势文件上传功效的事例,当中使用到了Jquery插件Ajaxupload,其能够达成单个文件和多文本上传功效。 

AjaxUpload

  Jquery插件AjaxUpload达成公文上传功效时不供给成立form表单,就能够完毕Ajax方式的文书上传,当然依照要求也足以成立form表单。

兵马未动粮草先行粮草先行职业

1、下载Jquery开发包和文件上传插件AjaxUpload。

2、创设uploadfile.html,并引进Jquery开荒包和AjaxUpload插件

<script src="js/jquery-1.3.js"></script>
<script src="js/ajaxupload.3.5.js"></script>

3、依据Jquery插件AjaxUpload的急需,创设二个触发Ajax文件上传功效的DIV

<ul> 
    <li id="example"> 
    <div id="upload_button">文件上传</div>
    <p>已上传的文件列表:</p> 
            <ol class="files"></ol>
</ul>

注释:由上边包车型客车代码大家能够看看Jquery插件AjaxUpload是基于upload_button那个DIV触发布公文件上传功用。 

前台JS代码

  在代码中本身设置了开关,依据须求能够相称上传文件类型,同期也得以安装是以Ajax情势实现单个文件上传仍旧八个公文上传。

$(document).ready(function(){
    var button = $('#upload_button'), interval;
    var fileType = "all",fileNum = "one"; 
    new AjaxUpload(button,{
        action: 'do/uploadfile.php',
        /*data:{
            'buttoninfo':button.text()
        },*/
        name: 'userfile',
        onSubmit : function(file, ext){
            if(fileType == "pic")
            {
                if (ext && /^(jpg|png|jpeg|gif)$/.test(ext)){
                    this.setData({
                        'info': '文件类型为图片'
                    });
                } else {
                    $('<li></li>').appendTo('#example .files').text('非图片类型文件,请重传');
                    return false;               
                }
            }

            button.text('文件上传中');

            if(fileNum == 'one')
                this.disable();

            interval = window.setInterval(function(){
                var text = button.text();
                if (text.length < 14){
                    button.text(text + '.');                    
                } else {
                    button.text('文件上传中');             
                }
            }, 200);
        },
        onComplete: function(file, response){
            if(response != "success")
                alert(response);

            button.text('文件上传');

            window.clearInterval(interval);

            this.enable();

            if(response == "success");
                $('<li></li>').appendTo('#example .files').text(file);                  
        }
    });

});

注释
第1行:$(document卡塔尔.ready(卡塔尔国函数,Jquery中的函数,形似于window.load,使用那个函数可在DOM载入就绪能够读取并决定期即时调用绑定的函数。

第3行:fileType和fileNum参数代表上传文件的档期的顺序和数码,暗中认可值为可上传全部项目文件,同时只好上传二个文书,如想上传图片文件或同期上传四个公文,可将那四个变量值变为pic和more。

第6~8行:POST到服务器的数据,你能够安装静态值也足以透过Jquery的DOM操作函数到手部分动态值,比如form表单中INPUT的值等。

第9行:等同于前端

<input type="file" name="userfile">

服务器端$_FILES[‘userfile’]

第10~36行:文件上传前触发的效能。

第11~21行:图片文件类型的过滤效果,Jquery
setData函数用来设置POST至劳动器端的值。

第25~26行:设置同期只上传一个文书依然多个文本,若是只上传三个文本,则将触及开关禁掉。假若要多传输几个文件,请在劳动器端PHP文件上传程序中装置MAXSIZE的值,当然上传文件的大大小小限定同期和PHP.INI文件中的设置也许有关。

第28~35行:在文书上传进程中每隔200皮秒动态更新壹次开关的文字,已兑现动态提醒的功力。window.setInterval函数用来每隔内定的小时就进行贰次停放的函数,人机联作时间单位为豪秒。

第37~49行:文件上传成效达成后触发的法力,依照重临值若是服务器端报错,则前端通过ALERT情势提示出错消息。

劳动器端PHP文件上传代码

  大意上是基于以前介绍的PHP文件上传效能代码实例教程整编,涉及到的文本上传大小的设置,出错音讯等证实皆是在那文中详尽表达。

$upload_dir = '../file/';
$file_path = $upload_dir . $_FILES['userfile']['name'];
$MAX_SIZE = 20000000;

echo $_POST['buttoninfo'];
if(!is_dir($upload_dir))
{
    if(!mkdir($upload_dir))
        echo "文件上传目录不存在并且无法创建文件上传目录";
    if(!chmod($upload_dir,0755))
        echo "文件上传目录的权限无法设定为可读可写";
}

if($_FILES['userfile']['size']>$MAX_SIZE)
    echo "上传的文件大小超过了规定大小";

if($_FILES['userfile']['size'] == 0)
    echo "请选择上传的文件";

if(!move_uploaded_file( $_FILES['userfile']['tmp_name'], $file_path))
    echo "复制文件失败,请重新上传"; 

switch($_FILES['userfile']['error'])
{
    case 0:
        echo "success" ;
        break;
    case 1:
        echo "上传的文件超过了 php.ini 中 upload_max_filesize 选项限制的值";
        break;
    case 2:
        echo "上传文件的大小超过了 HTML 表单中 MAX_FILE_SIZE 选项指定的值";
        break;
    case 3:
        echo "文件只有部分被上传";
        break;
    case 4:
        echo "没有文件被上传";
        break;
}

总结

  基本上前端Ajax文件上传触发成效和服务器端PHP文件上传功效的原型就介绍完结了,你能够依附自己需求对内外端代码进行补充,也能够将有个别效果独立出来,譬如文件类型、单个文件大概多文件上传功用。总的来讲Jquery插件AjaxUpload实现公文上传作用的采用依然相比易于的。

:PHP网址开拓教程-leapsoul.cn版权全数,转发时请以链接情势申明原始出处及本申明,谢谢。

.

.

.

来源:

引入js文件 – ajaxupload.js
引入java jar文件 – commons-fileupload-1.2.1.jar;commons-io-1.4.jar

上传js代码

//upload resume
new AjaxUpload('resume', {
    // Location of the server-side upload script
    // NOTE: You are not allowed to upload files to another domain
    action: '../resources/Reg1C/upload',
    // File upload name
    name: 'resume',
    // Fired after the file is selected
    // Useful when autoSubmit is disabled
    // You can return false to cancel upload
    // @param file basename of uploaded file
    // @param extension of that file
    onChange: function (file, extension) { },
    // Fired before the file is uploaded
    // You can return false to cancel upload
    // @param file basename of uploaded file
    // @param extension of that file
    onSubmit: function (file, extension)
    {
        if (!(extension && /^(doc|docx|pdf)$/i.test(extension)))
        {
            // extension is not allowed
            alert('Error: invalid file extension');
            // cancel upload
            return false;
        }
        // allow only 1 upload
        //this.disable();
    },
    // Fired when file upload is completed
    // WARNING! DO NOT USE "FALSE" STRING AS A RESPONSE!
    // @param file basename of uploaded file
    // @param response server response
    onComplete: function (file, response)
    {
        if ($(response).find("isSuccess").text() == "false")
        {
            alert($(response).find("msg").text());
            if ($(response).find("id").text() == "-1")
            {
                window.location.href = "../Home/index.jsp";
            }
            return;
        }
        else
        {
            $("#uploadMsg").html(file + " is uploaded!");
        }
    }
});

Java code: (RESTful )

@POST
@Path("upload")
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
    public ResponseVO upload() throws IOException {
ResponseVO responseVO = new ResponseVO();
Integer userId = SessionStoreManager.getUserId(request);
if (userId == null) {
responseVO.setId(ResponseVO.HOME_ALERT);
responseVO.setMsg("Your session is time out!");
return responseVO;
}
try {
// Create a factory for disk-based file items
FileItemFactory factory = new DiskFileItemFactory();
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// Parse the request
List<FileItem> items = upload.parseRequest(request);

// Process the uploaded items
Iterator<FileItem> iter = items.iterator();
while (iter.hasNext()) {
FileItem item = iter.next();
// Process a file upload
if (!item.isFormField()) {
String fileName = item.getName();
//comment out for .docx type will get a too long string
String contentType = item.getContentType();
if (!(Resume.PDF_CONTENT_TYPE.equals(contentType)
|| Resume.DOC_CONTENT_TYPE.equals(contentType)
|| Resume.DOCX_CONTENT_TYPE.equals(contentType))) {
responseVO.setIsSuccess(false);
responseVO.setMsg("MS Word or PDF files only.");
return responseVO;
}
long sizeInBytes = item.getSize();
if (sizeInBytes > Constants.MAX_RESUME_SIZE) {
responseVO.setIsSuccess(false);
responseVO.setMsg("Error uploading the resume file. Resume file size must be less than 1M.");
return responseVO;
}
byte[] data = item.get();
//Expert entityExpert = em.find(Expert.class, userId);
Resume entityResume = em.find(Resume.class, userId);
if (entityResume == null) {
entityResume = new Resume();
entityResume.setId(userId);
em.persist(entityResume);
}
entityResume.setContent(data);
entityResume.setContentType(contentType);

responseVO.setIsSuccess(true);
responseVO.setMsg("Upload sucess!" + item.getContentType());
}
}
} catch (Exception e) {
responseVO.setIsSuccess(false);
responseVO.setMsg("Upload failed!");
}

return responseVO;
}

相关文章

发表评论

电子邮件地址不会被公开。 必填项已用*标注

网站地图xml地图