最近專案(WEBFORM)碰到一個需求:上傳圖片後,按一個按鈕把圖片插入下方文字編輯格內。實做後碰到一個難點,因為頁面上不只一個FILEUPLOAD原件,如果另一個上傳檔案會觸發POSTBACK,讓另一個上傳地方的資訊被清除,考慮過後決定從簡單的方式解決,實做一個上傳圖片插入的頁面用IFRAME鑲在主頁面,這樣幾次POSTBACK都沒問題了。
以下是上傳的頁面:
前端
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div id="PhotoInsertDiv" style="margin-top:-4px">
<asp:FileUpload ID="PhotoInsert" runat="server" Width="175px"/>
<asp:Button ID="BtnUpload" runat="server"
Text="插入" Width="40px" BorderColor="#ADD1E4"
BorderStyle="Solid" BorderWidth="1px" AutoPostBack="false" OnClick="doInsert"></asp:Button>
</div>
</form>
</body>
</html>
後端
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Fileloadpage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void doInsert(object sender, EventArgs e)
{
string savePath = "";
Boolean fileOK = false;
String path = Server.MapPath("~/Upload/InsertImage/");
if (PhotoInsert.HasFile)
{
//強制檔名小寫
String fileExtension =
Path.GetExtension(PhotoInsert.FileName).ToLower();
//判斷格式
String[] allowedExtensions =
{".gif", ".png", ".jpeg", ".jpg"};
for (int i = 0; i < allowedExtensions.Length; i++)
{
if (fileExtension == allowedExtensions[i])
{
fileOK = true;
}
}
}
if (fileOK)
{
try
{
//檔案資料夾是否存在,否則新增一個
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
int i = 2;
string fileName = PhotoInsert.FileName.ToLower();
string tempfileName = fileName;
savePath = path + fileName;
//避免上傳重覆檔名,重新命名
while (File.Exists(savePath))
{
string[] fileNameArray = fileName.Split('.');
tempfileName = fileName.Substring(0, fileName.LastIndexOf('.')) + "(" + i + ")." + fileNameArray[fileNameArray.Count() - 1];
i++;
savePath = path + tempfileName;
}
PhotoInsert.SaveAs(savePath);
string imgUrl = Request.Url.AbsoluteUri.Replace("/fileloadpage.aspx", "");
//回傳呼叫主頁面的函式並帶入圖片路徑
Response.Write("<script> window.parent.callBack('" +imgUrl + "/Upload/InsertImage/" + tempfileName + "');</script>");
}
catch (Exception ex)
{
Console.Write(ex);
}
}
}
}
主頁面的JS 方法
把圖片插入另一個IFRAME
function callBack(path) {
$("#HTMLEditor_contentIframe").contents().find("body").append('<img alt="" src="' + path + '" />');
}
記得把上傳的頁面用IFRAME的方式嵌入主頁面 完成~