<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Upload.aspx.cs" Inherits="Demo.Upload" %>
<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>Uploadify 文件上傳示例</title>
<link href="js/uploadify/uploadify.css" rel="stylesheet" />
<script src="js/jquery-1.4.2.min.js"></script>
<script src="js/uploadify/swfobject.js"></script>
<script src="js/uploadify/jquery.uploadify.v2.1.4.min.js"></script>
<style>
#fileQueue { margin: 10px 0; }
.uploadify-queue-item { border: 1px solid #ddd; padding: 8px; margin: 5px 0; background: #fafafa; }
.uploadify-progress { height: 4px; background: #eee; overflow: hidden; }
.uploadify-progress-bar { height: 100%; background: #3498db; width: 0%; transition: width 0.3s; }
</style>
</head>
<body>
<h2>多檔案上傳 (支援 JPG/PNG/GIF, 最大 100KB)</h2>
<div id="fileQueue"></div>
<input type="file" name="uploadify" id="uploadify" />
<p>
<a href="javascript:$('#uploadify').uploadifyUpload()">開始上傳</a> |
<a href="javascript:$('#uploadify').uploadifyClearQueue()">清空隊列</a>
</p>
<script>
$(function() {
$('#uploadify').uploadify({
'uploader': 'js/uploadify/uploadify.swf',
'script': 'UploadHandler.ashx',
'cancelImg': 'js/uploadify/cancel.png',
'folder': 'UploadFiles/',
'queueID': 'fileQueue',
'auto': false, // 手動觸發上傳
'multi': true, // 多檔案
'fileExt': '*.jpg;*.jpeg;*.gif;*.png',
'fileDesc': '圖片檔案',
'sizeLimit': 102400, // 100KB
'buttonText': '選擇圖片',
'width': 120,
'height': 30,
'onSelect': function(event, queueID, fileObj) {
console.log('已選擇:', fileObj.name, '大小:', fileObj.size);
},
'onCancel': function(event, queueID, fileObj) {
console.log('取消上傳:', fileObj.name);
},
'onComplete': function(event, queueID, fileObj, response, data) {
console.log('單檔完成:', fileObj.name, '回應:', response);
},
'onAllComplete': function(event, data) {
alert('上傳完成:' + data.filesUploaded + ' 個檔案,' + data.errors + ' 個錯誤');
},
'onError': function(event, queueID, fileObj, errorObj) {
alert('錯誤:' + fileObj.name + ' - ' + errorObj.type + ': ' + errorObj.info);
}
});
});
</script>
</body>
</html>
<%@ WebHandler Language="C#" Class="UploadHandler" %>
using System;
using System.Web;
using System.IO;
public class UploadHandler : IHttpHandler {
public void ProcessRequest(HttpContext context) {
context.Response.ContentType = "text/plain";
context.Response.Charset = "utf-8";
try {
HttpPostedFile file = context.Request.Files["Filedata"];
if (file == null || file.ContentLength == 0) {
context.Response.Write("0");
return;
}
// 取得儲存路徑 (從前端傳來的 folder 參數)
string folder = context.Request["folder"] ?? "UploadFiles/";
string uploadPath = context.Server.MapPath("~/" + folder);
// 建立目錄
if (!Directory.Exists(uploadPath)) {
Directory.CreateDirectory(uploadPath);
}
// 檔名處理:避免衝突、過濾危險字元
string fileName = Path.GetFileName(file.FileName);
fileName = SanitizeFileName(fileName);
string savePath = Path.Combine(uploadPath, fileName);
// 同名檔案處理:加上時間戳
if (File.Exists(savePath)) {
string ext = Path.GetExtension(fileName);
string name = Path.GetFileNameWithoutExtension(fileName);
fileName = name + "_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ext;
savePath = Path.Combine(uploadPath, fileName);
}
// 儲存
file.SaveAs(savePath);
// 回傳成功 (Uploadify 預期回傳 "1" 表示成功)
context.Response.Write("1");
} catch (Exception ex) {
context.Response.Write("0");
// 記錄錯誤日誌
// Log.Error(ex);
}
}
private string SanitizeFileName(string fileName) {
// 移除路徑遍歷字元、特殊字元
foreach (char c in Path.GetInvalidFileNameChars()) {
fileName = fileName.Replace(c, '_');
}
return fileName;
}
public bool IsReusable { get { return false; } }
}
| 選項 | 類型 | 說明 |
|---|---|---|
| uploader | string | uploadify.swf 路徑 (Flash 檔案) |
| script | string | 後端處理器 URL (.ashx/.php/.jsp) |
| folder | string | 伺服器儲存相對路徑 |
| queueID | string | 顯示上傳隊列的容器 ID |
| auto | boolean | true=選檔即上傳, false=手動觸發 |
| multi | boolean | true=允許多檔 |
| fileExt | string | 允許副檔名,分號分隔 |
| fileDesc | string | 檔案選擇對話框顯示的說明 |
| sizeLimit | number | 單檔大小限制 (bytes) |
| buttonText | string | 按鈕顯示文字 |
| width/height | number | 按鈕尺寸 |
Uploadify 基於 Flash,2020 年後瀏覽器全面封鎖 Flash。請遷移至以下方案:
async function uploadFiles(files) {
const formData = new FormData();
for (const file of files) {
formData.append('files', file);
}
const response = await fetch('/api/upload', {
method: 'POST',
body: formData
});
return response.json();
}
// 進度顯示需使用 XMLHttpRequest
function uploadWithProgress(files, onProgress) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
const formData = new FormData();
files.forEach(f => formData.append('files', f));
xhr.upload.onprogress = e => {
if (e.lengthComputable) onProgress(e.loaded / e.total);
};
xhr.onload = () => resolve(JSON.parse(xhr.responseText));
xhr.onerror = () => reject(new Error('上傳失敗'));
xhr.open('POST', '/api/upload');
xhr.send(formData);
});
}
import Uppy from '@uppy/core';
import Dashboard from '@uppy/dashboard';
import XHRUpload from '@uppy/xhr-upload';
const uppy = new Uppy()
.use(Dashboard, { target: '#uppy', inline: true })
.use(XHRUpload, { endpoint: '/api/upload' });
uppy.on('complete', (result) => {
console.log('成功:', result.successful);
console.log('失敗:', result.failed);
});
Dropzone.options.myDropzone = {
url: '/api/upload',
maxFilesize: 2, // MB
acceptedFiles: 'image/*',
addRemoveLinks: true,
dictDefaultMessage: '拖曳檔案到此或點擊選擇'
};
multipart/form-data (ASP.NET Core: IFormFile, Java: MultipartFile)xhr.upload.onprogress 或 Uppy 內建事件Uploadify 曾是 jQuery 時代最流行的上傳元件,但隨著 Flash 退出歷史舞台,已完成歷史使命。維護舊專案時可參考本文配置;新專案務必採用 HTML5 原生方案,獲得更好的相容性、安全性與使用者體驗。