<%@ Page Language="C#" AutoEventWireup="true" CodeFile="uploadfile.aspx.cs" Inherits="uploadfile" %>
<!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 runat="server">
<title>無標題頁</title>
<script src="Resource/jquery/jquery-1.4.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
jQuery.extend({
CreateUploadIframe: function (id, uri) {
//create frame
var frameId="UploadFrame";
if(id!=undefined && id!=""){
frameId=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.src=uri;
}
io.style.position = 'absolute';
io.style.top = '-1000px';
io.style.left = '-1000px';
document.body.appendChild(io);
return io
},
CreateUploadForm: function (id, uri) {
//create form
var formId="UploadForm";
if(id!=undefined && id!=""){
formId=id;
}
var form = $('<form action="'+uri+'" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');
//set form attributes
$(form).css('position', 'absolute');
$(form).css('top', '500px');
$(form).css('left', '100px');
$(form).appendTo('body');
return form;
},
CloneFilesToCreatedForm:function(oldFormId, createdFormId){
var form=$("#"+createdFormId);
$("#"+oldFormId+" input[type=file]").each(function(i){
//clone each file and append the old file control to the created form.
//reset newid, new name and append old file control to the created form that only for fix IE bug.
alert("id:"+$(this).attr("id")+"name:"+$(this).attr("name"));
var newId=(new Date()).getTime().toString();
var cloneFile=$(this).clone();
$(cloneFile).attr('id', newId);
$(cloneFile).attr('name', newId);
$(this).before(cloneFile);
alert('1');
$(this).appendTo(form);
alert("id:"+$(this).attr("id")+"name:"+$(this).attr("name"));
});
},
IframeUploadFiles: function (s) {
// TODO introduce global settings, allowing the client to modify them for all requests
s = jQuery.extend({}, jQuery.ajaxSettings, s);
//get id for create form and iframe.
var id = new Date().getTime();
var frameId = 'UploadFrame' + id;
var formId = 'UploadForm' + id;
var form = jQuery.CreateUploadForm(formId,s.url);
var frame = jQuery.CreateUploadIframe(frameId, s.secureUri);
if(s.defaultForm!=undefined && s.defaultForm!=""){
jQuery.CloneFilesToCreatedForm(s.defaultForm, formId);
}
//submit the form.
try{
$(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) {
alert('Upload files happened error!');
}
}
});
</script>
<script type="text/javascript">
function UploadAllFiles() {
$.IframeUploadFiles({
url:'UploadFIleHandler.ashx',
defaultForm:'form1',
secureUri:false
})
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<div id="UploadFilesWrapper" style="border:solid 1px #369;">
<p class="uploadfile">
<input type="button" value="增加" style="width:100px; height:30px;" onclick="addFile('UploadFilesWrapper')"/>
<input type="button" id="buttonUpload" style="width:100px; height:30px;" value="上傳" onclick="UploadAllFiles()" />
</p>
<p>
<input id="UploadFileDefault" type="file" size="50" name="UploadFileDefault" />
</p>
<p>
<input type="button" onclick="getfilename($('#fileToUpload'))" value="get file path"/>
<input type="button" onclick="RemoveFilePath($('#fileToUpload'))" value="remove file path"/>
</p>
<input type="submit" value="submit to current form" />
<input type="text" name="tst1" />
<input type="radio" name="tst2" />
</div>
</div>
</form>
<div id="ajaxMsg"></div>
<script type="text/javascript">
//show upload files result
function ShowMessageForUploadFile(msg) {
$("#ajaxMsg").html(msg);
}
// get upload file name by path.
function GetFileNameByPath(path) {
//get path
if (path == undefined || path == "") {
return "";
} else {
var index = path.lastIndexOf("\\");
if (index > 0) {
return path.substring(index + 1, path.length);
} else {
return path;
}
}
}
//create input of file
function addFile(target) {
//create input type='file'
var fileName = (new Date()).getTime();
var p = document.createElement("p");
var file = document.createElement("input");
file.setAttribute("type", "file")
file.setAttribute("name", fileName)
file.setAttribute("id",fileName);
file.setAttribute("size", "50")
p.appendChild(file)
var button = document.createElement("input");
button.setAttribute("type", "button");
button.setAttribute("value", "移除")
$(button).click(function(){
RemoveEachFile(this)
});
p.appendChild(button);
document.getElementById(target).appendChild(p);
}
//remove the each file container with file input
function RemoveEachFile(o) {
while (o.tagName != "P") {
o = o.parentNode;
}
o.parentNode.removeChild(o);
}
//removed value of file contorl
function RemoveFilePath(obj) {
var objFile = $(obj)[0];
objFile.outerHTML = objFile.outerHTML.replace(/(value=\").+\"/i, "$1\"");
}
//get
function getfilename(o) {
var name = GetFileNameByPath($(o).val());
}
</script>
</body>
</html>
//ashx
<%@ WebHandler Language="C#" Class="UploadFIleHandler" %>
using System;
using System.Web;
public class UploadFIleHandler : IHttpHandler {
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";
HttpFileCollection fileConnection = Request.Files;
foreach (string ctlName in fileConnection)
{
//擷取上傳的檔案
string newFileName = Guid.NewGuid().ToString();
HttpPostedFile file = fileConnection[ctlName];
//使用guid產生新檔案名稱
if (file.FileName == "")
{
//未上傳檔案
//Response.Write("<script>parent.ShowMessageForUploadFile('');</script>");
}
//輸出js,使用parent對象得到父頁的引用
else
{
//儲存檔案
newFileName += System.IO.Path.GetExtension(file.FileName);//注意加上副檔名
try
{
file.SaveAs(Server.MapPath("~/uploadfiles/" + newFileName));
//Response.Write("<script>parent.ShowMessageForUploadFile('upload file success.')</script>");
}
catch
{
//Response.Write("<script>alert('儲存檔案失敗!\\n請檢查檔案夾是否有寫入許可權!');</script>");
}
}
}
Response.Write("<script>parent.ShowMessageForUploadFile('upload file success.')</script>");
}
public bool IsReusable {
get {
return false;
}
}
}