台灣最大程式設計社群網站
線上人數
651
 
會員總數:245619
討論主題:189317
歡迎您免費加入會員
討論區列表 >> AJAX / JSON / jQuery >> jQuery fileupload - 你要開啓或儲存 XXX.aspx
[]  
[我要回覆]
1
回應主題 加入我的關注話題 檢舉此篇討論 將提問者加入個人黑名單
jQuery fileupload - 你要開啓或儲存 XXX.aspx
價值 : 100 QP  點閱數:791 回應數:7
樓主

學習者
門外漢
0 5
82 13
發送站內信

小弟在網路上找到一個jQuery fileupload C#範例,在自己的電腦上使用visual 2013測試都沒有問題,但是如果放到inetpub/wwwroot,從另外一台電腦連線使用,當操作檔案上傳時,即出現你要開啓或儲存 XXX.aspx的對話框訊息,百思不解,尋遍google也沒訊息,望請大大們指教,謝謝。

網址:
http://blog.xuite.net/tolarku/blog/230091854-%5BjQuery%2BASP.NET%5D++%E5%A4%9A%E6%AA%94%E6%A1%88%E5%90%8C%E6%99%82%E4%B8%8A%E5%82%B3+-+%E4%BD%BF%E7%94%A8+jQuery+File+Upload

原文址
https://blueimp.github.io/jQuery-File-Upload/





搜尋相關Tags的文章: [ jquery ] , [ ajax ] , [ js ] , [ fileupload ] , [ c# ] ,
本篇文章發表於2016-06-04 07:45
1樓
回應

迷路
捐贈 VP 給 迷路 檢舉此回應
你確定你的iis有設定支援.NET嗎?
本篇文章回覆於2016-06-04 09:31
== 簽名檔 ==
--未登入的會員無法查看對方簽名檔--
2樓
回應

浩瀚星空
捐贈 VP 給 浩瀚星空 檢舉此回應
你確定你的運行檔案指向是正確的嗎??

至少也po一下你的程式碼相關吧。要不然讓人家問半天。
本篇文章回覆於2016-06-04 09:36
== 簽名檔 ==
--未登入的會員無法查看對方簽名檔--
3樓
作者回應

學習者
檢舉此回應
To 1F
有開,嘗試運行其他.NET程式皆無問題
To 2F
我嘗試過直接下載該範例網站裡面的 sample檔,也是同樣情況 = ="
http://blog.xuite.net/tolarku/blog/230091854-%5BjQuery%2BASP.NET%5D++%E5%A4%9A%E6%AA%94%E6%A1%88%E5%90%8C%E6%99%82%E4%B8%8A%E5%82%B3+-+%E4%BD%BF%E7%94%A8+jQuery+File+Upload

以上,感謝指教^^

本篇文章回覆於2016-06-04 12:29
== 簽名檔 ==
--未登入的會員無法查看對方簽名檔--
4樓
作者回應

學習者
檢舉此回應
二台電腦,連上同一個sample測試如下:
https://blueimp.github.io/jQuery-File-Upload/

第一台電腦 會出現你要開啓或儲存XXX.aspx對話框的電腦:沒有進度條,一次只能點選一個圖檔上傳,上傳能夠成功
第二台電腦 不會出現對話框的電腦:有進度條,一次能夠點選多個圖檔上傳,上傳能夠成功

@@"第一台電腦可謂乾淨,似乎除了WIN7以外什麼都沒灌~ 放在inetpub/wwwroot,用二台電腦從外部連上,情況也呈現上述的差異.
本篇文章回覆於2016-06-05 10:43
== 簽名檔 ==
--未登入的會員無法查看對方簽名檔--
5樓
作者回應

學習者
檢舉此回應
簡附程式碼,勞請前輩們指點迷跡

=========================================================================================================================
fileupload.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="fileupload.aspx.cs" Inherits="tester0724.fileupload" %>

<!DOCTYPE html>

<html>
<head>

<!-- Force latest IE rendering engine or ChromeFrame if installed -->
<!--[if IE]>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<![endif]-->
<meta charset="utf-8"/>
<title>jQuery File Upload Demo</title>
<meta name="description" content="File Upload widget with multiple file selection, drag&amp;drop support, progress bars, validation and preview images, audio and video for jQuery. Supports cross-domain, chunked and resumable file uploads and client-side image resizing. Works with any server-side platform (PHP, Python, Ruby on Rails, Java, Node.js, Go etc.) that supports standard HTML form file uploads."/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<!-- Bootstrap styles -->
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css"/>
<!-- Generic page styles -->
<link rel="stylesheet" href="Upload_Code/css/style.css"/>
<!-- blueimp Gallery styles -->
<link rel="stylesheet" href="http://blueimp.github.io/Gallery/css/blueimp-gallery.min.css"/>
<!-- CSS to style the file input field as button and adjust the Bootstrap progress bars -->
<link rel="stylesheet" href="Upload_Code/css/jquery.fileupload.css"/>
<link rel="stylesheet" href="Upload_Code/css/jquery.fileupload-ui.css"/>
<!-- CSS adjustments for browsers with JavaScript disabled -->
<noscript><link rel="stylesheet" href="Upload_Code/css/jquery.fileupload-noscript.css"/></noscript>
<noscript><link rel="stylesheet" href="Upload_Code/css/jquery.fileupload-ui-noscript.css"/></noscript>


</head>
<body>


<div class="container">

<form id="form1" runat="server">
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click"/>


</form>
<!-- The file upload form used as target for the file upload widget -->
<form id="fileupload" action="UploadProgress.aspx" method="POST" enctype="multipart/form-data">


<!-- Redirect browsers with JavaScript disabled to the origin page -->
<!-- <noscript><input type="hidden" name="redirect" value="http://blueimp.github.io/jQuery-File-Upload/"></noscript>-->
<!-- The fileupload-buttonbar contains buttons to add/delete files and start/cancel the upload -->
<div class="row fileupload-buttonbar">
<div class="col-lg-7">
<!-- The fileinput-button span is used to style the file input field as button -->
<span class="btn btn-success fileinput-button">
<i class="glyphicon glyphicon-plus"></i>
<span>選擇檔案</span>
<input type="file" name="files[]" multiple>
</span>
<button type="submit" class="btn btn-primary start">
<i class="glyphicon glyphicon-upload"></i>
<span>檔案上傳</span>
</button>
<button type="reset" class="btn btn-warning cancel">
<i class="glyphicon glyphicon-ban-circle"></i>
<span>取消上傳</span>
</button>
<button type="button" class="btn btn-danger delete">
<i class="glyphicon glyphicon-trash"></i>
<span>刪除檔案</span>
</button>
<input type="checkbox" class="toggle">
<!-- The global file processing state -->
<span class="fileupload-process"></span>
</div>
<!-- The global progress state -->
<div class="col-lg-5 fileupload-progress fade">
<!-- The global progress bar -->
<div class="progress progress-striped active" role="progressbar" aria-valuemin="0" aria-valuemax="100">
<div class="progress-bar progress-bar-success" style="width:0%;"></div>
</div>
<!-- The extended global progress state -->
<div class="progress-extended">&nbsp;</div>
</div>
</div>
<!-- The table listing the files available for upload/download -->
<table role="presentation" class="table table-striped"><tbody class="files"></tbody></table>
</form>
<br>
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">上傳說明</h3>
</div>
<div class="panel-body">
<ul>
<li>上傳檔案大小限制在 <strong>50 MB</strong> 以下。</li>
<li>限制上傳檔案類型: (<strong>JPG, GIF, PNG 及 MS Office 系列檔案</strong>) .</li> <!--上傳類型的限制設定在 main.js-->
</ul>
</div>
</div>
</div>
<!-- The blueimp Gallery widget -->

<!-- The template to display files available for upload -->
<script id="template-upload" type="text/x-tmpl">
{% for (var i=0, file; file=o.files[i]; i++) { %}
<tr class="template-upload fade">
<td>
<span class="preview"></span>
</td>
<td>
<p class="name">{%=file.name%}</p>
<strong class="error text-danger"></strong>
</td>
<td>
<p class="size">Processing...</p>
<div class="progress progress-striped active" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0"><div class="progress-bar progress-bar-success" style="width:0%;"></div></div>
</td>
<td>
{% if (!i && !o.options.autoUpload) { %}
<button class="btn btn-primary start" disabled>
<i class="glyphicon glyphicon-upload"></i>
<span>Start</span>
</button>
{% } %}
{% if (!i) { %}
<button class="btn btn-warning cancel">
<i class="glyphicon glyphicon-ban-circle"></i>
<span>Cancel</span>
</button>
{% } %}
</td>
</tr>
{% } %}
</script>
<!-- The template to display files available for download -->
<script id="template-download" type="text/x-tmpl">
{% for (var i=0, file; file=o.files[i]; i++) { %}
<tr class="template-download fade">
<td>
<span class="preview">
{% if (file.thumbnailUrl) { %}
<a href="{%=file.url%}" target="_blank" title="{%=file.name%}" download="{%=file.name%}" data-gallery><img src="{%=file.thumbnailUrl%}"></a>
{% } %}
</span>
</td>
<td>
<p class="name">
{% if (file.url) { %}
<a href="{%=file.url%}" target="_blank" title="{%=file.name%}" download="{%=file.name%}" {%=file.thumbnailUrl?'data-gallery':''%}>{%=file.name%}</a>
{% } else { %}
<span>{%=file.name%}</span>
{% } %}
</p>
{% if (file.error) { %}
<div><span class="label label-danger">Error</span> {%=file.error%}</div>
{% } %}
</td>
<td>
<span class="size">{%=o.formatFileSize(file.size)%}</span>
</td>
<td>
{% if (file.deleteUrl) { %}
<button class="btn btn-danger delete" data-type="{%=file.deleteType%}" data-url="{%=file.deleteUrl%}" {% if (file.deletewithcredentials) { %} data-xhr-fields='{"withCredentials":true}' {% } %}>
<i class="glyphicon glyphicon-trash"></i>
<span>Delete</span>
</button>
<input type="checkbox" name="delete" value="1" class="toggle">
{% } else { %}><button class="btn btn-warning cancel">
<i class="glyphicon glyphicon-ban-circle"></i>
<span>Cancel</span>
</button>
{% } %}
</td>
</tr>
{% } %}
</script>
<script src="Upload_Code/js/jquery_1.11.0.min.js"></script>
<!-- The jQuery UI widget factory, can be omitted if jQuery UI is already included -->
<!-- jquery.ui.widget.js 不能省略,否則已上傳及要上傳之清單會看不到-->
<script src="Upload_Code/js/vendor/jquery.ui.widget.js"></script>
<!-- The Templates plugin is included to render the upload/download listings -->
<script src="http://blueimp.github.io/JavaScript-Templates/js/tmpl.min.js"></script>
<!-- The Load Image plugin is included for the preview images and image resizing functionality -->
<script src="http://blueimp.github.io/JavaScript-Load-Image/js/load-image.all.min.js"></script>
<!-- The Canvas to Blob plugin is included for image resizing functionality -->
<script src="http://blueimp.github.io/JavaScript-Canvas-to-Blob/js/canvas-to-blob.min.js"></script>
<!-- Bootstrap JS is not required, but included for the responsive demo navigation -->
<script src="Upload_Code/css/bootstrap-3.1.1-dist/js/bootstrap.min.js"></script>
<!-- blueimp Gallery script -->
<script src="http://blueimp.github.io/Gallery/js/jquery.blueimp-gallery.min.js"></script>
<!-- The Iframe Transport is required for browsers without support for XHR file uploads -->
<script src="https://blueimp.github.io/JavaScript-Load-Image/js/load-image.js"></script>
<script src="https://blueimp.github.io/JavaScript-Load-Image/js/load-image-ios.js"></script>
<script src="https://blueimp.github.io/JavaScript-Load-Image/js/load-image-orientation.js"></script>
<script src="https://blueimp.github.io/JavaScript-Load-Image/js/load-image-meta.js"></script>
<script src="https://blueimp.github.io/JavaScript-Load-Image/js/load-image-exif.js"></script>
<script src="https://blueimp.github.io/JavaScript-Load-Image/js/load-image-exif-map.js"></script>





<script src="Upload_Code/js/jquery.iframe-transport.js"></script>
<script src="Upload_Code/js/load-image.all.min.js"></script>
<!-- The File Upload 基本檔案上傳套件 -->
<script src="Upload_Code/js/jquery.fileupload.js"></script>
<!-- The File Upload 檔案上傳處理套件 (processing plugin) -->
<script src="Upload_Code/js/jquery.fileupload-process.js"></script>
<!-- The File Upload 檔案上傳圖片檔預覽套件 (image preview & resize plugin) -->
<script src="Upload_Code/js/jquery.fileupload-image.js"></script>
<!--<script src="js/load-image.min.js"></script>-->
<!-- The File Upload 檔案上傳音樂檔預覽套件 (audio preview plugin) 若不允許上傳影片,可以不用載入-->
<script src="Upload_Code/js/jquery.fileupload-audio.js"></script>
<!-- The File Upload 檔案上傳影片預覽套件 (video preview plugin) 若不允許上傳影片,可以不用載入 -->
<script src="Upload_Code/js/jquery.fileupload-video.js"></script>
<!-- The File Upload 檔案上傳驗證套件 (validation plugin) -->
<script src="Upload_Code/js/jquery.fileupload-validate.js"></script>
<!-- The File Upload 檔案上傳使用者介面套件 (user interface plugin) -->
<script src="Upload_Code/js/jquery.fileupload-ui.js"></script>
<script>var fileuploadurl = "UploadProgress.aspx";</script>
<script src="Upload_Code/js/main.js"></script>


</body>
</html>

========================================================================================================================================
UploadHandler.aspx


<%@ Page ContentType="application/json" %>

<%@ Import Namespace="System.Collections.Generic" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Runtime.Serialization.Json" %>
<%@ Import Namespace="System.Runtime.Serialization" %>
<%@ Import Namespace="System.Runtime.Serialization.Json" %>
<%@ Import Namespace="System.Linq" %>

<script language="C#" runat="server">

// Sergey Dobychin
// dobychin@gmail.com
// May, 2014

// don't forget about IIS site settings
//<system.web>
// <httpRuntime executionTimeout="9999999" maxRequestLength="2097151" />
//</system.web>
//<system.webServer>
// <security>
// <requestFiltering>
// <requestLimits maxAllowedContentLength="2147483648" />
// </requestFiltering>
// </security>
//</system.webServer>

//private static readonly FilesDisposition FILES_DISPOSITION = FilesDisposition.ServerRoot;
private static readonly FilesDisposition FILES_DISPOSITION = FilesDisposition.Absolute;
private string FILES_PATH;
private string AccountEncoded; //編碼過後的目錄名稱

private static readonly string FILE_QUERY_VAR = "file";
private static readonly string FILE_GET_CONTENT_TYPE = "application/octet-stream";

private static readonly int ATTEMPTS_TO_WRITE = 3;
private static readonly int ATTEMPT_WAIT = 100; //msec

private static readonly int BUFFER_SIZE = 4 * 1024 * 1024;

private enum FilesDisposition
{
ServerRoot,
HandlerRoot,
Absolute
}

private static class HttpMethods
{
public static readonly string GET = "GET";
public static readonly string POST = "POST";
public static readonly string DELETE = "DELETE";
}

[DataContract]
private class FileResponse
{
[DataMember]
public string name;
[DataMember]
public long size;
[DataMember]
public string type;
[DataMember]
public string url;
[DataMember]
public string error;
[DataMember]
public string deleteUrl;
[DataMember]
public string deleteType;
}

[DataContract]
private class UploaderResponse
{
[DataMember]
public FileResponse[] files;

public UploaderResponse(FileResponse[] fileResponses)
{
files = fileResponses;
}
}

private string CreateFileUrl(string fileName, FilesDisposition filesDisposition)
{
switch (filesDisposition)
{
case FilesDisposition.ServerRoot:
// 1. files directory lies in root directory catalog WRONG
return String.Format("{0}{1}/{2}", Request.Url.GetLeftPart(UriPartial.Authority),
FILES_PATH, Path.GetFileName(fileName));

case FilesDisposition.HandlerRoot:
// 2. files directory lays in current page catalog WRONG
return String.Format("{0}{1}{2}/{3}", Request.Url.GetLeftPart(UriPartial.Authority),
Path.GetDirectoryName(Request.CurrentExecutionFilePath).Replace(@"\", @"/"), FILES_PATH, Path.GetFileName(fileName));

case FilesDisposition.Absolute:
// 3. files directory lays anywhere YEAH
return String.Format("{0}?{1}={2}", Request.Url.AbsoluteUri, FILE_QUERY_VAR, HttpUtility.UrlEncode(Path.GetFileName(fileName)));
default:
return String.Empty;
}
}

private FileResponse CreateFileResponse(string fileName, long size, string error)
{
return new FileResponse()
{
name = Path.GetFileName(fileName),
size = size,
type = String.Empty,
url = CreateFileUrl(fileName, FILES_DISPOSITION),
//url = @"http://ed.chu.edu.tw/staff/GetFile.ashx?s=" + AccountEncoded + "&f=" + HttpUtility.UrlEncode(Path.GetFileName(fileName)),
error = error,
deleteUrl = CreateFileUrl(fileName, FilesDisposition.Absolute),
deleteType = HttpMethods.POST
//deleteType = HttpMethods.DELETE
};
}

private void SerializeUploaderResponse(List<FileResponse> fileResponses)
{
DataContractJsonSerializer Serializer = new DataContractJsonSerializer(typeof(UploaderResponse));

Serializer.WriteObject(Response.OutputStream, new UploaderResponse(fileResponses.ToArray()));
}

private void FromStreamToStream(Stream source, Stream destination)
{
int BufferSize = source.Length >= BUFFER_SIZE ? BUFFER_SIZE : (int)source.Length;
long BytesLeft = source.Length;

byte[] Buffer = new byte[BufferSize];

int BytesRead = 0;

while (BytesLeft > 0)
{
BytesRead = source.Read(Buffer, 0, BytesLeft > BufferSize ? BufferSize : (int)BytesLeft);

destination.Write(Buffer, 0, BytesRead);

BytesLeft -= BytesRead;
}
}

protected void Page_Load(object sender, EventArgs e)
{

//將帳號編碼過: 帳號094169 => 目錄zqvytq
string Account = HttpContext.Current.User.Identity.Name;
AccountEncoded = "";
string EncodeString = "zyxwvutsrq"; // 編碼規則: 0=>z 1=y 2=x ..... 9=q
for (int i=0;i<Account.Length;i++)
{
AccountEncoded = AccountEncoded + EncodeString.Substring( Convert.ToInt16(Account.Substring(i,1)) ,1);
}
FILES_PATH = HttpContext.Current.Server.MapPath(".") + "/Source/Uploads/"; // +AccountEncoded;

string FilesPath;

switch (FILES_DISPOSITION)
{
case FilesDisposition.ServerRoot:
FilesPath = Server.MapPath(FILES_PATH);
break;
case FilesDisposition.HandlerRoot:
FilesPath = Server.MapPath(Path.GetDirectoryName(Request.CurrentExecutionFilePath) + FILES_PATH);
break;
case FilesDisposition.Absolute:
FilesPath = FILES_PATH;
break;
default:
Response.StatusCode = 500;
Response.StatusDescription = "Configuration error (FILES_DISPOSITION)";
return;
}

// prepare directory
if (!Directory.Exists(FilesPath))
{
Directory.CreateDirectory(FilesPath);
}


string QueryFileName = Request[FILE_QUERY_VAR]; //從POST資料取出上傳的檔案名稱
string FullFileName = null; //用來放完整路徑
string ShortFileName = null; //存放檔名

//if (!String.IsNullOrEmpty(QueryFileName))
// 判斷上傳的檔名變數是否有內容
if (QueryFileName != null) // param specified, but maybe in wrong format (empty). else user will download json with listed files
{
ShortFileName = HttpUtility.UrlDecode(QueryFileName); //取出檔名
FullFileName = String.Format(@"{0}\{1}", FilesPath, ShortFileName); // 結合完整路徑與檔名~~成為完整PATH

if (QueryFileName.Trim().Length == 0 || !File.Exists(FullFileName)) //判斷檔案是否存在
{
Response.StatusCode = 404;
Response.StatusDescription = "File not found";

Response.End();
return;
}
}

if (Request.HttpMethod.ToUpper() == HttpMethods.GET) // ---- GET 的處理片段 -----------------------------------
{
if (FullFileName != null)
{
Response.ContentType = FILE_GET_CONTENT_TYPE; // http://www.digiblog.de/2011/04/android-and-the-download-file-headers/ :)
Response.AddHeader("Content-Disposition", String.Format("attachment; filename={0}{1}", Path.GetFileNameWithoutExtension(ShortFileName), Path.GetExtension(ShortFileName).ToUpper()));

using (FileStream FileReader = new FileStream(FullFileName, FileMode.Open, FileAccess.Read))
{
FromStreamToStream(FileReader, Response.OutputStream);

Response.OutputStream.Close();
}

Response.End();
return;
}
else // FullFileName == null
{
//檔案列表
List<FileResponse> FileResponseList = new List<FileResponse>();
// get your files (names)
string[] FileNames = Directory.GetFiles(FilesPath);
// Now read the creation time for each file
//DateTime[] creationTimes = new DateTime[FileNames.Length];
//for (int i = 0; i < FileNames.Length; i++)
// creationTimes[i] = new FileInfo(FileNames[i]).CreationTime;
// sort it
//Array.Sort(creationTimes, FileNames);

DateTime TimeRange = DateTime.Now.AddDays(-1); //一天內

foreach (string FileName in FileNames)
{
if (new FileInfo(FileName).CreationTime > TimeRange)
{
FileResponseList.Add(CreateFileResponse(FileName, new FileInfo(FileName).Length, String.Empty));
}
}

SerializeUploaderResponse(FileResponseList);
}
}
else if (Request.HttpMethod.ToUpper() == HttpMethods.POST && Request.QueryString["file"] == null) // ---- POST 的處理片段 -----------------------------------
{
List<FileResponse> FileResponseList = new List<FileResponse>();

for (int FileIndex = 0; FileIndex < Request.Files.Count; FileIndex++) //利用 HttpPostedFile 方式來將檔案寫入到 Server
{
HttpPostedFile File = Request.Files[FileIndex];

string FileName = String.Format(@"{0}\{1}", FilesPath, Path.GetFileName(File.FileName));
string ErrorMessage = String.Empty;

for (int Attempts = 0; Attempts < ATTEMPTS_TO_WRITE; Attempts++)
{
ErrorMessage = String.Empty;

if (System.IO.File.Exists(FileName))
{
FileName = String.Format(@"{0}\{1}_{2:yyyyMMddHHmmss.fff}{3}", FilesPath, Path.GetFileNameWithoutExtension(FileName), DateTime.Now, Path.GetExtension(FileName));
}
File.SaveAs(FileName);
break;
}

//FileResponseList.Add(CreateFileResponse(File.FileName, File.ContentLength, ErrorMessage));
FileResponseList.Add(CreateFileResponse(FileName, File.ContentLength, ErrorMessage));
}

SerializeUploaderResponse(FileResponseList);
}
//else if (Request.HttpMethod.ToUpper() == HttpMethods.DELETE)
// else if (Request.HttpMethod.ToUpper() == HttpMethods.POST && Request.QueryString["file"] == null) // ---- POST 的處理片段 -----------------------------------
else if (Request.HttpMethod.ToUpper() == HttpMethods.POST && Request.QueryString["file"] != null) // 刪除檔案之片段
{
bool SuccessfullyDeleted = true;

try
{
File.Delete(FullFileName);
}
catch
{
SuccessfullyDeleted = false;
}

Response.Write(String.Format("{{\"{0}\":{1}}}", ShortFileName, SuccessfullyDeleted.ToString().ToLower()));
}
else
{
Response.StatusCode = 405;
Response.StatusDescription = "Method not allowed";
Response.End();

return;
}


Response.End();
}



</script>
=========================================================================================================================
UploadProgress.aspx


<%@ Page ContentType="application/json" %>
<%@ Import Namespace="System.Collections.Generic" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Runtime.Serialization.Json" %>
<%@ Import Namespace="System.Runtime.Serialization" %>
<%@ Import Namespace="System.Runtime.Serialization.Json" %>
<%@ Import Namespace="System.Linq" %>

<script language="C#" runat="server">
// 檔案的上傳路徑
private string Upload_Directory;// = HttpContext.Current.Server.MapPath(".") + "/Source/Uploads/";//"../Source/Uploads/";
private static readonly int BUFFER_SIZE = 4 * 1024 * 1024;

[DataContract]
private class FileResponse
{
[DataMember]
public string name;
[DataMember]
public long size;
[DataMember]
public string type;
[DataMember]
public string url;
[DataMember]
public string error;
[DataMember]
public string deleteUrl;
[DataMember]
public string deleteType;
}

[DataContract]
private class UploaderResponse
{
[DataMember]
public FileResponse[] files;
public UploaderResponse(FileResponse[] fileResponses)
{
files = fileResponses;
}
}
private FileResponse CreateFileResponse(string fileName, long size, string error)
{
return new FileResponse()
{
name = Path.GetFileName(fileName),
size = size,
type = String.Empty,
url = String.Format("{0}?{1}={2}", Request.Url.AbsoluteUri, "file", HttpUtility.UrlEncode(Path.GetFileName(fileName))),
error = error,
deleteUrl = String.Format("{0}?{1}={2}", Request.Url.AbsoluteUri, "file", HttpUtility.UrlEncode(Path.GetFileName(fileName))),
deleteType = "POST"
};
}

private void SerializeUploaderResponse(List<FileResponse> fileResponses)
{ // 將物件序列化為 JavaScript 物件標記法 (JSON) 以及將 JSON 資料還原序列化為物件
DataContractJsonSerializer Serializer = new DataContractJsonSerializer(typeof(UploaderResponse));
// 將物件序列化為可以對應至 JavaScript 物件標記法 (JSON) 的 XML。 使用 XmlWriter 來寫入所有的物件資料,包括起始 XML 項目、內容和結尾項目。
Serializer.WriteObject(Response.OutputStream, new UploaderResponse(fileResponses.ToArray()));
}

private void FromStreamToStream(Stream source, Stream destination) // 搭配 GET method 使用
{
int BufferSize = source.Length >= BUFFER_SIZE ? BUFFER_SIZE : (int)source.Length;
long BytesLeft = source.Length;
byte[] Buffer = new byte[BufferSize];
int BytesRead = 0;
while (BytesLeft > 0)
{
BytesRead = source.Read(Buffer, 0, BytesLeft > BufferSize ? BufferSize : (int)BytesLeft);
destination.Write(Buffer, 0, BytesRead);
BytesLeft -= BytesRead;
}
}

protected void Page_Load(object sender, EventArgs e)
{
Upload_Directory = (string)Session["NewstrFolderPath"] + "/";
string QueryFileName = Request["file"]; //從POST資料取出上傳的檔案名稱
string FullFileName = null; //用來放完整路徑
string ShortFileName = null; //存放檔名
// 判斷上傳的檔名變數是否有內容
if (QueryFileName != null) // param specified, but maybe in wrong format (empty). else user will download json with listed files
{
ShortFileName = HttpUtility.UrlDecode(QueryFileName); //取出檔名
FullFileName = String.Format(@"{0}\{1}", Upload_Directory, ShortFileName); // 結合完整路徑與檔名~~成為完整PATH
if (QueryFileName.Trim().Length == 0 || !File.Exists(FullFileName)) //判斷檔案是否存在
{
Response.StatusCode = 404;
Response.StatusDescription = "File not found";
Response.End();
return;
}
}

if (Request.HttpMethod.ToUpper() == "GET") // ---- GET 的處理片段 -----------------------------------
{
if (FullFileName != null)
{
Response.ContentType = "application/octet-stream"; // http://www.digiblog.de/2011/04/android-and-the-download-file-headers/ :)
Response.AddHeader("Content-Disposition", String.Format("attachment; filename={0}{1}", Path.GetFileNameWithoutExtension(ShortFileName), Path.GetExtension(ShortFileName).ToUpper()));
using (FileStream FileReader = new FileStream(FullFileName, FileMode.Open, FileAccess.Read))
{
FromStreamToStream(FileReader, Response.OutputStream);
Response.OutputStream.Close();
}
Response.End();
return;
}
else // FullFileName == null
{
//檔案列表
List<FileResponse> FileResponseList = new List<FileResponse>();
string[] FileNames = Directory.GetFiles(Upload_Directory);
DateTime TimeRange = DateTime.Now.AddDays(-1); //一天內

foreach (string FileName in FileNames)
{
if (new FileInfo(FileName).CreationTime > TimeRange)
{
FileResponseList.Add(CreateFileResponse(FileName, new FileInfo(FileName).Length, String.Empty));
}
}
SerializeUploaderResponse(FileResponseList);
}
} //EOF --- if (Request.HttpMethod.ToUpper() == "GET")
else if (Request.HttpMethod.ToUpper() == "POST" && Request.QueryString["file"] == null) // ---- POST 的處理片段 -----------------------------------
{
List<FileResponse> FileResponseList = new List<FileResponse>();
for (int FileIndex = 0; FileIndex < Request.Files.Count; FileIndex++) //利用 HttpPostedFile 方式來將檔案寫入到 Server
{
HttpPostedFile File = Request.Files[FileIndex];
string FileName = String.Format(@"{0}\{1}", Upload_Directory, Path.GetFileName(File.FileName));
string ErrorMessage = String.Empty;
if (System.IO.File.Exists(FileName)) // 檔名重複時的處理,增加序號 _yyyyMMddHHmmss.fff
{
FileName = String.Format(@"{0}\{1}_{2:yyyyMMddHHmmss.fff}{3}", Upload_Directory, Path.GetFileNameWithoutExtension(FileName), DateTime.Now, Path.GetExtension(FileName));
}
File.SaveAs(FileName); // 將檔案寫入 Server 端
FileResponseList.Add(CreateFileResponse(FileName, File.ContentLength, ErrorMessage));
}
SerializeUploaderResponse(FileResponseList);
} // EOF --- if (Request.HttpMethod.ToUpper() == "POST" && Request.QueryString["file"] == null)
// 刪除檔案之片段 ---------------------------------------
else if (Request.HttpMethod.ToUpper() == "POST" && Request.QueryString["file"] != null)
{
bool SuccessfullyDeleted = true;
try
{ File.Delete(FullFileName); }
catch
{ SuccessfullyDeleted = false; }
Response.Write(String.Format("{{\"{0}\":{1}}}", ShortFileName, SuccessfullyDeleted.ToString().ToLower()));
}
else // 不是 GET 也不是 POST 也不是做 DELETE
{
Response.StatusCode = 405;
Response.StatusDescription = "Method not allowed";
Response.End();
return;
}
Response.End();
}
</script>



本篇文章回覆於2016-06-05 23:43
== 簽名檔 ==
--未登入的會員無法查看對方簽名檔--
6樓
作者回應

學習者
檢舉此回應
如上述程式碼,選好圖片檔後按下上傳按鈕就會出現"你要開啓或儲存UploadProgress.aspx",再用第三台電腦測試,則是出現"未知檔案UploadProgress.aspx"等訊息......
本篇文章回覆於2016-06-12 20:39
== 簽名檔 ==
--未登入的會員無法查看對方簽名檔--
7樓
最有價值解答

小愛
檢舉此回應
用實體路徑設定下載資料夾試試
本篇文章回覆於2016-06-28 00:47
== 簽名檔 ==
--未登入的會員無法查看對方簽名檔--
   
1

回覆
如要回應,請先登入.