需求是這樣的:上傳圖片時希望能先預覽,而且頁面還有其他的文字欄位要一起儲存。因此流程設計成:先上傳圖片取得路徑,再把路徑與其他文字一起寫入資料庫;同時為圖片產生一張縮圖。以下只寫圖片上傳的部分,文字欄位在 Ajax 裡直接傳參數即可;若要支援多圖,改一下迴圈就行。
整個功能不需要另開頁面,在一個頁面內就能完成。
// 以 Ajax 呼叫後台方法儲存資料
function SaveData() {
var filename = document.getElementById("idFile").value;
var result = test_test_aspx.SaveData(filename).value;
if (result) {
alert("保存成功!");
}
return false;
}
// 依容器大小等比縮放預覽圖
function DrawImage(ImgD) {
var preW = 118;
var preH = 118;
var image = new Image();
image.src = ImgD.src;
if (image.width > 0 && image.height > 0) {
if (image.width / image.height >= preW / preH) {
if (image.width > preW) {
ImgD.width = preW;
ImgD.height = (image.height * preW) / image.width;
} else {
ImgD.width = image.width;
ImgD.height = image.height;
}
ImgD.alt = image.width + "x" + image.height;
} else {
if (image.height > preH) {
ImgD.height = preH;
ImgD.width = (image.width * preH) / image.height;
} else {
ImgD.width = image.width;
ImgD.height = image.height;
}
ImgD.alt = image.width + "x" + image.height;
}
}
}
// idFile 內容改變時先清空預覽狀態
function FileChange(Value) {
document.getElementById("showImg").style.display = "none";
document.getElementById("idImg").width = 10;
document.getElementById("idImg").height = 10;
document.getElementById("idImg").alt = "";
document.getElementById("idImg").src = Value;
}
<div class="cbs">
<div class="l"><label>圖片:</label></div>
<div>
<input id="idFile" name="pic" type="file" runat="server"
onchange="FileChange(this.value);" />
</div>
</div>
<div class="cbs">
<div class="l"><label>預覽:</label></div>
<div>
<!-- 實現預覽 -->
<img id="idImg" height="0" width="0" src="" alt="" onload="DrawImage(this);" />
<!-- 查看時顯示原圖;idImg 加上 runat="server" 會報錯,故另備一個 -->
<img id="showImg" width="118" height="118" alt="" runat="server" style="display:none"/>
</div>
</div>
[Ajax.AjaxMethod()]
public bool SaveData(string fileNamePath)
{
string serverFileName = "";
string sThumbFile = "";
string sSavePath = "~/Files/";
int intThumbWidth = 118;
int intThumbHeight = 118;
string sThumbExtension = "thumb_";
try
{
FileInfo file = new FileInfo(fileNamePath);
string fileNameExt = file.Extension;
// 1. 驗證副檔名是否合法
if (!CheckFileExt(fileNameExt)) { return false; }
// 2. 產生隨機檔名,避免覆寫既有檔案
string fileName = GetFileName() + fileNameExt;
if (!sSavePath.EndsWith("/")) { sSavePath = sSavePath + "/"; }
// 3. 依日期分層存放
sSavePath += DateTime.Now.ToString("yyyyMM") + "/"
+ DateTime.Now.ToString("dd") + "/";
serverFileName = sSavePath + fileName;
string toFileFullPath = HttpContext.Current.Server.MapPath(sSavePath);
if (!Directory.Exists(toFileFullPath))
{
Directory.CreateDirectory(toFileFullPath);
}
string toFile = toFileFullPath + fileName;
// 4. 寫入檔案
WebClient myWebClient = new WebClient();
myWebClient.Credentials = CredentialCache.DefaultCredentials;
FileStream fs = new FileStream(fileNamePath, FileMode.Open, FileAccess.Read);
BinaryReader r = new BinaryReader(fs);
byte[] postArray = r.ReadBytes((int)fs.Length);
Stream postStream = myWebClient.OpenWrite(toFile, "PUT");
if (postStream.CanWrite)
{
postStream.Write(postArray, 0, postArray.Length);
}
postStream.Close();
// 5. 產生縮圖
using (System.Drawing.Image sourceImage =
System.Drawing.Image.FromFile(HttpContext.Current.Server.MapPath(serverFileName)))
{
int width = sourceImage.Width;
int height = sourceImage.Height;
int smallWidth;
int smallHeight;
// 依長寬比計算中間圖尺寸
if (((decimal)width) / height <= ((decimal)intThumbWidth) / intThumbHeight)
{
smallWidth = intThumbWidth;
smallHeight = intThumbWidth * height / width;
}
else
{
smallWidth = intThumbHeight * width / height;
smallHeight = intThumbHeight;
}
// 若縮圖檔名已存在,附加序號
int file_append = 0;
sThumbFile = sThumbExtension
+ Path.GetFileNameWithoutExtension(fileName) + fileNameExt;
while (File.Exists(HttpContext.Current.Server.MapPath(sSavePath + sThumbFile)))
{
file_append++;
sThumbFile = sThumbExtension
+ Path.GetFileNameWithoutExtension(fileName)
+ file_append.ToString() + fileNameExt;
}
string smallImagePath = HttpContext.Current.Server.MapPath(sSavePath) + sThumbFile;
// 先畫中間圖(高品質縮放)
using (System.Drawing.Image bitmap = new System.Drawing.Bitmap(smallWidth, smallHeight))
using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap))
{
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
g.Clear(Color.Black);
g.DrawImage(sourceImage,
new System.Drawing.Rectangle(0, 0, smallWidth, smallHeight),
new System.Drawing.Rectangle(0, 0, width, height),
System.Drawing.GraphicsUnit.Pixel);
}
// 再從中間圖裁切置中,畫成最終縮圖
using (System.Drawing.Image bitmap1 = new System.Drawing.Bitmap(intThumbWidth, intThumbHeight))
using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap1))
{
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
g.Clear(Color.Black);
int lwidth = (smallWidth - intThumbWidth) / 2;
int bheight = (smallHeight - intThumbHeight) / 2;
g.DrawImage(bitmap,
new Rectangle(0, 0, intThumbWidth, intThumbHeight),
lwidth, bheight, intThumbWidth, intThumbHeight,
GraphicsUnit.Pixel);
bitmap1.Save(smallImagePath, System.Drawing.Imaging.ImageFormat.Jpeg);
return true;
}
}
}
catch
{
// 出錯時刪除已寫入的檔案,避免留下垃圾
System.IO.File.Delete(HttpContext.Current.Server.MapPath(serverFileName));
return false;
}
}
/// <summary>
/// 檢查是否為合法的上傳副檔名
/// </summary>
private bool CheckFileExt(string _fileExt)
{
string[] allowExt = new string[] { ".gif", ".jpg", ".jpeg" };
for (int i = 0; i < allowExt.Length; i++)
{
if (allowExt[i] == _fileExt) { return true; }
}
return false;
}
/// <summary>
/// 以時間戳加隨機數產生檔名
/// </summary>
public static string GetFileName()
{
Random rd = new Random();
StringBuilder serial = new StringBuilder();
serial.Append(DateTime.Now.ToString("yyyyMMddHHmmssff"));
serial.Append(rd.Next(0, 999999).ToString());
return serial.ToString();
}
程式能跑,但正式環境前有幾點務必處理。
副檔名校驗不足以防禦惡意檔案。CheckFileExt() 只看副檔名,而副檔名是使用者可以任意竄改的。上傳後務必以 Image.FromStream() 實際載入一次驗證它真的是圖片,並把檔案存到 Web 根目錄之外或目錄瀏覽與執行權限皆關閉的位置。
catch 抓到例外就全部吞掉。目前的寫法一律 return false,發生問題時完全不知道原因。請至少記錄 Exception 到日誌,正式環境再把友善訊息回給使用者。
用 WebClient 搬檔案是繞路。既然檔案已在伺服器上,直接用 File.Copy() 或 FileStream 就足夠,不必多繞一圈 Web 請求。
縮圖應該用 Save() 搭配 ImageFormat 並指定/JPEG 品質參數,否則預設壓縮品質偏高、檔案偏大。另外 Clear(Color.Black) 對 PNG 透明圖會產生黑底,若需保留透明請存成 PNG 並改用 Color.Transparent。
別忘了限制檔案大小。目前沒有任何上限,使用者上傳一個幾百 MB 的檔案就可能讓伺服器記憶體爆掉。
最後,這套做法依賴已不建議用於新專案的 ASP.NET WebForms 與 Ajax.AjaxMethod。若今天重新開始,改用 ASP.NET Core 的 IFormFile 接收上傳,搭配 ImageSharp 或 SkiaSharp 產生縮圖,程式碼會短很多,跨平台也不是問題。