無重新整理的的檔案上傳

來源:互聯網
上載者:User

標籤:des   style   blog   http   java   使用   os   io   

一、

通過iframe來實現無重新整理的的檔案上傳,其實是有重新整理的,只是在iframe裡面隱藏了而已

 

簡單的原理說明:

<form id="form1" method="post" action="upload.do" enctype="multipart/form-data"  target="uploadframe" >

<input type="file" id="upload" name="檔案上傳" />

</form>

<iframe id="uploadframe" name="result_frame"   style="visibility:hidden;"></iframe>

 

form裡面的target要與iframe裡面的id的值相等,指示是form相應了post事件,也就是post時間相應的時候重新整理的是iframe而不是整個頁面。

 

二、

利用jQuery的外掛程式AjaxFileUpload 可以簡單地實現這個非同步上傳的效果      外掛程式地址: http://www.phpletter.com/Our-Projects/AjaxFileUpload/

 

 <script type="text/javascript" language="javascript" src="js/jquery.js"></script>

 <script type="text/javascript" language="javascript" src="js/ajaxfileupload.js"></script>

 

 

 

function ajaxFileUpload()

{

$("#loading")

.ajaxStart(function(){

$(this).show();           

})

.ajaxComplete(function(){

$(this).hide();           

});

 

$.ajaxFileUpload

(

{

url:‘Upload.ashx‘,

secureuri:false,

fileElementId:‘fileToUpload‘,

dataType: ‘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;

 

}

 

 

<input id="fileToUpload" type="file" size="45" name="fileToUpload">

<input type="button" id="buttonUpload" onclick="return ajaxFileUpload();">

       上傳</input>

 

 

Upload.ashx

 

 

 

if (Request.Files.Count > 0)

{

HttpPostedFile file = Request.Files[0];

string msg = "";

string error = "";

if (file.ContentLength == 0)

error = "檔案長度為0";

else

{

file.SaveAs(Server.MapPath("file") + "\\" + Path.GetFileName(file.FileName));

msg = "上傳成功";

}

string result = "{ error:‘" + error + "‘, msg:‘" + msg + "‘}";

Response.Write(result);

Response.End();

}

 

 

 

 

PS:ajaxfileupload.js代碼

 

 

 

jQuery.extend({

 

createUploadIframe: function(id, uri)

{

//create frame

var frameId = ‘jUploadFrame‘ + id;

 

if(window.ActiveXObject) {

var io = document.createElement(‘<iframe id="‘ + frameId + ‘" name="‘ + frameId + ‘" />‘);

if(typeof uri== ‘boolean‘){

io.src = ‘javascript:false‘;

}

else if(typeof uri== ‘string‘){

io.src = uri;

}

}

else {

var io = document.createElement(‘iframe‘);

io.id = frameId;

io.name = frameId;

}

io.style.position = ‘absolute‘;

io.style.top = ‘-1000px‘;

io.style.left = ‘-1000px‘;

 

document.body.appendChild(io);

 

return io           

},

createUploadForm: function(id, fileElementId)

{

//create form   

var formId = ‘jUploadForm‘ + id;

var fileId = ‘jUploadFile‘ + id;

var form = $(‘<form  action="" method="POST" name="‘ + formId + ‘" id="‘ + formId + ‘" enctype="multipart/form-data"></form>‘);   

var oldElement = $(‘#‘ + fileElementId);

var newElement = $(oldElement).clone();

$(oldElement).attr(‘id‘, fileId);

$(oldElement).before(newElement);

$(oldElement).appendTo(form);

//set attributes

$(form).css(‘position‘, ‘absolute‘);

$(form).css(‘top‘, ‘-1200px‘);

$(form).css(‘left‘, ‘-1200px‘);

$(form).appendTo(‘body‘);       

return form;

},

 

ajaxFileUpload: function(s) {

// TODO introduce global settings, allowing the client to modify them for all requests, not only timeout       

s = jQuery.extend({}, jQuery.ajaxSettings, s);

var id = new Date().getTime()       

var form = jQuery.createUploadForm(id, s.fileElementId);

var io = jQuery.createUploadIframe(id, s.secureuri);

var frameId = ‘jUploadFrame‘ + id;

var formId = ‘jUploadForm‘ + id;       

// Watch for a new set of requests

if ( s.global && ! jQuery.active++ )

{

jQuery.event.trigger( "ajaxStart" );

}           

var requestDone = false;

// Create the request object

var xml = {}  

if ( s.global )

jQuery.event.trigger("ajaxSend", [xml, s]);

// Wait for a response to come back

var uploadCallback = function(isTimeout)

{           

var io = document.getElementById(frameId);

try

{               

if(io.contentWindow)

{

xml.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null;

xml.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document;

 

}else if(io.contentDocument)

{

xml.responseText = io.contentDocument.document.body?io.contentDocument.document.body.innerHTML:null;

xml.responseXML = io.contentDocument.document.XMLDocument?io.contentDocument.document.XMLDocument:io.contentDocument.document;

}                       

}catch(e)

{

jQuery.handleError(s, xml, null, e);

}

if ( xml || isTimeout == "timeout")

{               

requestDone = true;

var status;

try {

status = isTimeout != "timeout" ? "success" : "error";

 

// Make sure that the request was successful or notmodified

if ( status != "error" )

{

// process the data (runs the xml through httpData regardless of callback)

var data = jQuery.uploadHttpData( xml, s.dataType );   

// If a local callback was specified, fire it and pass it the data

if ( s.success )

s.success( data, status );

 

// Fire the global callback

if( s.global )

jQuery.event.trigger( "ajaxSuccess", [xml, s] );

} else

jQuery.handleError(s, xml, status);

} catch(e)

{

status = "error";

jQuery.handleError(s, xml, status, e);

}

 

// The request was completed

if( s.global )

jQuery.event.trigger( "ajaxComplete", [xml, s] );

 

// Handle the global AJAX counter

if ( s.global && ! --jQuery.active )

jQuery.event.trigger( "ajaxStop" );

 

// Process result

if ( s.complete )

s.complete(xml, status);

 

jQuery(io).unbind()

 

setTimeout(function()

{    try

{

$(io).remove();

$(form).remove();   

 

} catch(e)

{

jQuery.handleError(s, xml, null, e);

}                                   

 

}, 100)

 

xml = null

 

}

}

// Timeout checker

if ( s.timeout > 0 )

{

setTimeout(function(){

// Check to see if the request is still happening

if( !requestDone ) uploadCallback( "timeout" );

}, s.timeout);

}

try

{

// var io = $(‘#‘ + frameId);

var form = $(‘#‘ + formId);

$(form).attr(‘action‘, s.url);

$(form).attr(‘method‘, ‘POST‘);

$(form).attr(‘target‘, frameId);

if(form.encoding)

{

form.encoding = ‘multipart/form-data‘;               

}

else

{               

form.enctype = ‘multipart/form-data‘;

}           

$(form).submit();

 

} catch(e)

{           

jQuery.handleError(s, xml, null, e);

}

if(window.attachEvent){

document.getElementById(frameId).attachEvent(‘onload‘, uploadCallback);

}

else{

document.getElementById(frameId).addEventListener(‘load‘, uploadCallback, false);

}        

return {abort: function () {}};   

 

},

 

uploadHttpData: function( r, type ) {

var data = !type;

data = type == "xml" || data ? r.responseXML : r.responseText;

// If the type is "script", eval it in global context

if ( type == "script" )

jQuery.globalEval( data );

// Get the JavaScript object, if JSON is used.

if ( type == "json" )

eval( "data = " + data );

// evaluate scripts within html

if ( type == "html" )

jQuery("<div>").html(data).evalScripts();

//alert($(‘param‘, data).each(function(){alert($(this).attr(‘value‘));}));

return data;

}

})

 

 三、純iframe實現上傳

upload.ashx

 

 

 

//<%@ WebHandler Language="C#" class="upload" %>

 

using System;

using System.Web;

 

public class upload : IHttpHandler {

private string Js(string v) {//此函數進行js的轉義替換的,防止字串中輸入了‘後造成回調輸出的js中字串不閉合

if (v == null) return "";

return v.Replace("‘", @"\‘");

}

//下面就是一個簡單的樣本,儲存上傳的檔案,如果要驗證上傳的尾碼名,得自己寫,還有寫資料庫什麼的

public void ProcessRequest (HttpContext context) {

HttpRequest Request = context.Request;

HttpResponse Response = context.Response;

HttpServerUtility Server = context.Server;

//指定輸出頭和編碼

Response.ContentType = "text/html";

Response.Charset = "utf-8";

 

HttpPostedFile f = Request.Files["upfile"];//擷取上傳的檔案

string des = Request.Form["des"]//擷取描述

,newFileName=Guid.NewGuid().ToString();//使用guid產生新檔案名稱

 

if (f.FileName == "")//未上傳檔案

Response.Write("<script>parent.UpdateMsg(‘‘,‘‘);</script>");//輸出js,使用parent對象得到父頁的引用

else { //儲存檔案

newFileName += System.IO.Path.GetExtension(f.FileName);//注意加上副檔名

try {

f.SaveAs(Server.MapPath("~/uploads/" + newFileName));//如果要儲存到其他地方,注意修改這裡

 

//調用父過程更新內容,注意要對des變數進行js轉義替換,防止字串不閉合提示錯誤

Response.Write("<script>parent.UpdateMsg(‘" +Js(des)+ "‘,‘" + newFileName + "‘)</script>");

}

catch {

Response.Write("<script>alert(‘儲存檔案失敗!\\n請檢查檔案夾是否有寫入許可權!‘);</script>");//如果儲存失敗,輸出js提示儲存失敗

}

 

}

}

 

public bool IsReusable {

get {

return false;

}

}

 

}

 

 

test.htm

 

 

<!!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">>

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="content-type" content="text/html;charset=utf-8" />

<title>使用隱藏的Iframe實現ajax無重新整理上傳</title>

</head>

<body>

<script type="text/javascript">

function UpdateMsg(des,filename){//此函數用來提供給提交到的頁面如upload.ashx輸出js的回調,更新當前頁面的資訊

if(filename==‘‘){alert(‘未上傳檔案!‘);return false;}

document.getElementById(‘ajaxMsg‘).innerHTML=‘你在表單中輸入的“檔案描述”為:‘+des+‘<br/>‘

+‘上傳的圖片為:<a href="uploads/‘+filename+‘" target="_blank">‘+filename+‘</a>‘;

}

 

function check(f){

if(f.des.value==‘‘){

alert(‘請輸入檔案描述!‘);f.des.focus();return false;

}

if(f.upfile.value==‘‘){

alert(‘請選擇檔案!‘);f.upfile.focus();return false;

}

}

</script>

<!--隱藏的iframe來接受表單提交的資訊-->

<iframe name="ajaxifr" style="display:none;"></iframe>

<!--這裡設定target="ajaxifr",這樣表單就提交到iframe裡面了,和平時未設定target屬性時預設提交到當前頁面-->

<!--注意一點的是使用iframe時在提交到的頁面可以直接輸出js來操作父頁面的資訊,一般的ajax提交文本資訊時你需要返回資訊,如果是js資訊你還得eval下-->

<form method="post" enctype="multipart/form-data" action="upload.ashx" target="ajaxifr" onsubmit="return check(this)">

檔案描述:<input type="text" name="des" /><br >

選擇檔案:<input type="file" name="upfile" /><br >

<input type="submit" value="提交" />

</form>

<!--放入此div用來實現上傳的結果-->

<div id="ajaxMsg"></div>

</body>

</html>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.