在次以前我也不怎么了解图片上传!
在使用swfupload当中遇到的问题
1、图片保存到指定的根目录下的文件中后,无法获取图片路径?????
2、图片保存到数据库中后,不知道如何下手提取数据库中的路径并显示图片到网页?????
3、当上边的一系列问题都解决后,在IE浏览器中可以正常显示以及功能的实现,但是在火狐中不能够保存图片路径到数据库(可以上传、预览、保存到指定根目录文件夹中)。因为在解决第一个问题的时候使用的是session来存储值,但是在火狐中运行时.aspx.cs中的session取值为空!???????????
功能实现的步骤:
1、下载swfupload整理!!!!
在http://yunpan.cn/QCZWHYsAR2Usk(提取码:5f86)可以下载整理好的swfupload,把文件解压后复制到网站的根目录下
2、应用swfupload中的内容
建立一个功能页面 IDCardInfo.aspx
<script src="../SWFupload/swfupload.js" type="text/javascript"></script>
<script src="../SWFupload/handlers.js" type="text/javascript"></script>
<script type="text/javascript">
var swfu;
window.onload = function () {
swfu = new SWFUpload({
// Backend Settings
upload_url: "/ashx/upload.ashx",
post_params : {
"ASPSESSID" : "<%=Session.SessionID %>"
},
// File Upload Settings
file_size_limit : "2 MB",
file_types : "*.jpg;*.gif",
file_types_description : "JPG Images",
file_upload_limit : 0, // Zero means unlimited
// Event Handler Settings - these functions as defined in Handlers.js
// The handlers are not part of SWFUpload but are part of my website and control how
// my website reacts to the SWFUpload events.
swfupload_preload_handler : preLoad,
swfupload_load_failed_handler : loadFailed,
file_queue_error_handler : fileQueueError,
file_dialog_complete_handler : fileDialogComplete,
upload_progress_handler : uploadProgress,
upload_error_handler : uploadError,
upload_success_handler : ShowMsg,
upload_complete_handler : uploadComplete,
// Button settings
button_image_url : "/SWFupload/images/XPButtonNoText_160x22.png",
button_placeholder_id : "spanButtonPlaceholder",
button_width: 160,
button_height: 22,
button_text : '<span class="button">请选择图片<span class="buttonSmall">(2 MB Max)</span></span>',
button_text_style : '.button { font-family: Helvetica, Arial, sans-serif; font-size: 14pt; } .buttonSmall { font-size: 10pt; }',
button_text_top_padding: 1,
button_text_left_padding: 5,
// Flash Settings
flash_url : "/SWFupload/swfupload.swf", // Relative to this file
flash9_url : "/SWFupload/swfupload_FP9.swf", // Relative to this file
custom_settings : {
upload_target : "divFileProgressContainer"
},
// Debug Settings
debug: false
});
}
//在页面上显示上传成功的图片。
function ShowMsg(file, serverData)
{//serverData:从服务端返回的数据
var data=serverData.split(":");
if(data[0]=="ok"){
document.getElementById("imgok").src=data[1];
}
}
</script>
这是页面中只需要一次swfupload的情况
<script type="text/javascript">
$(function () {
getimag();
getimag1();
})
function getimag(){
var swfu = new SWFUpload({
// Backend Settings
upload_url:<strong> </strong>"ashx/upload.ashx",
post_params : {
"ASPSESSID" : "<%=Session.SessionID %>"
},
// File Upload Settings
file_size_limit : "2 MB",
file_types : "*.jpg;*.gif",
file_types_description : "JPG Images",
file_upload_limit : 0, // Zero means unlimited
// Event Handler Settings - these functions as defined in Handlers.js
// The handlers are not part of SWFUpload but are part of my website and control how
// my website reacts to the SWFUpload events.
swfupload_preload_handler : preLoad,
swfupload_load_failed_handler : loadFailed,
file_queue_error_handler : fileQueueError,
file_dialog_complete_handler : fileDialogComplete,
upload_progress_handler : uploadProgress,
upload_error_handler : uploadError,
upload_success_handler : ShowMsg,
upload_complete_handler : uploadComplete,
// Button settings
button_image_url : "SWFupload/images/XPButtonNoText_160x22.png",
button_placeholder_id : "spanButtonPlaceholder",
button_width: 160,
button_height: 22,
button_text : '<span class="button">请选择图片</span>',
button_text_style : '.button { font-family: Helvetica, Arial, sans-serif; font-size: 14pt; }',
button_text_top_padding: 1,
button_text_left_padding: 45,
// Flash Settings
flash_url : "SWFupload/swfupload.swf", // Relative to this file
flash9_url : "SWFupload/swfupload_FP9.swf", // Relative to this file
custom_settings : {
upload_target : "divFileProgressContainer"
},
// Debug Settings
debug: false
});
//在页面上显示上传成功的图片。
function ShowMsg(file, serverData)
{//serverData:从服务端返回的数据
var data=serverData.split(":");
if(data[0]=="ok"){
document.getElementById("ctl00_ContentPlaceHolder1_imgok").src=data[1];
}
}
}
function getimag1(){
var swfu1 = new SWFUpload({
// Backend Settings
upload_url: "ashx/upload.ashx",
post_params : {
"ASPSESSID" : "<%=Session.SessionID %>"
},
// File Upload Settings
file_size_limit : "2 MB",
file_types : "*.jpg;*.gif",
file_types_description : "JPG Images",
file_upload_limit : 0, // Zero means unlimited
// Event Handler Settings - these functions as defined in Handlers.js
// The handlers are not part of SWFUpload but are part of my website and control how
// my website reacts to the SWFUpload events.
swfupload_preload_handler : preLoad,
swfupload_load_failed_handler : loadFailed,
file_queue_error_handler : fileQueueError,
file_dialog_complete_handler : fileDialogComplete,
upload_progress_handler : uploadProgress,
upload_error_handler : uploadError,
upload_success_handler : ShowMsg1,
upload_complete_handler : uploadComplete,
// Button settings
button_image_url : "SWFupload/images/XPButtonNoText_160x22.png",
button_placeholder_id : "span1",
button_width: 160,
button_height: 22,
button_text : '<span class="button">请选择图片</span>',
button_text_style : '.button { font-family: Helvetica, Arial, sans-serif; font-size: 14pt; }',
button_text_top_padding: 1,
button_text_left_padding: 45,
// Flash Settings
flash_url : "SWFupload/swfupload.swf", // Relative to this file
flash9_url : "SWFupload/swfupload_FP9.swf", // Relative to this file
custom_settings : {
upload_target : "div3"
},
// Debug Settings
debug: false
});
//在页面上显示上传成功的图片。
function ShowMsg1(file, serverData)
{//serverData:从服务端返回的数据
// alert(serverData)
var data=serverData.split(":");
if(data[0]=="ok"){
document.getElementById("ctl00_ContentPlaceHolder1_img1").src=data[1];
}
}
}
</script>
这是网页中需要两次的情况,页面效果为
3、保存图片到指定的根目录文件夹中
在ashx(一般处理程序文件夹)中创建 upload.ashx
using System;
using System.Web;
using System.Web.SessionState;
public class upload : IHttpHandler,IRequiresSessionState {
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/plain";
//HttpCookie cookies = new HttpCookie("validate");
HttpPostedFile file = context.Request.Files["Filedata"];//获取上传的文件.
string fileName = System.IO.Path.GetFileName(file.FileName); //context.Session.Add("src", fileName);
string fileExtion = System.IO.Path.GetExtension(file.FileName);
if (fileExtion == ".jpg")
{
file.SaveAs(context.Server.MapPath("../admin/upload/" + fileName));
context.Session.Add("src", "upload/" + fileName);
//cookies["validate"] = "upload/" + fileName;
//context.Response.AppendCookie(cookies);
//context.Session["src"] = "upload/" + fileName;
context.Response.Write("ok:admin/upload/" + fileName);
//string saveDir = "../admin/upload/" + DateTime.Now.Year + "/" + DateTime.Now.Month + "/" + DateTime.Now.Day + "/";
//Directory.CreateDirectory(Path.GetDirectoryName(context.Server.MapPath(saveDir)));//建立文件夹
//string fullDir = saveDir + System.Data.Common.Common.GetStreamMD5(file.InputStream) + fileExtion;//将文件进行MD5运算作为新的文件的名称.
//file.SaveAs(context.Server.MapPath(fullDir));
//context.Response.Write("ok:" + fullDir);
}
else
{
throw new Exception("类型错误!!");
}
}
public bool IsReusable {
get {
return false;
}
}
}
4、保存到数据库
1)、使用session来存储图片路径,在upload.ashx中的
context.Session.Add("src", "upload/" + fileName);
2)、后台代码 IDCardInfo.aspx.cs
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using DAL;
using Model;
using System.Drawing;
public partial class IDCardInfo : System.Web.UI.Page
{
Company comp;
public string addrs = "";
public string scode = "block";
public string cman = "block";
public string cmanfz = "block";
public string cidcard = "block";
public int cid = 0;
protected void Page_Load(object sender, EventArgs e)
{
SessionRebulid mysession = new SessionRebulid();
mysession.RebulidSessionhy();
if (Session["userhy"] == null)
{
Response.Redirect("login.aspx");
}
if (!IsPostBack)
{
comp = (Company)Session["userhy"];
if (comp != null)
{
cid = comp.CID;
ViewState["cid"] = comp.CID;
ViewState["uid"] = comp.UID;
Bind(comp.CID);
}
}
}
private void Bind(int cid)
{
comp = DAL.CompanyServices.GetByID(cid);
if (comp != null)
{
if (comp.Cidcard != "")
{
if (comp.Cidcard.StartsWith("admin") || comp.Cidcard.StartsWith("Admin"))
{
imgok.Src= comp.Cidcard;
}
else
{
imgok.Src = "admin/" + comp.Cidcard;
}
}
else
{
imgok.Src = "admin/upload/nopic.jpg";
}
if (comp.Ccode != "")
{
if (comp.Ccode.StartsWith("admin") || comp.Ccode.StartsWith("Admin"))
{
img1.Src = comp.Ccode;
}
else
{
img1.Src = "admin/" + comp.Ccode;
}
}
else
{
img1.Src = "admin/upload/nopic.jpg";
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
Company comp = new Company();
if (ViewState["cid"] != null)
{
comp= CompanyServices.GetByID(Convert.ToInt32(ViewState["cid"]));
}
else
{
comp = new Model.Company();
}
if (Session["src"] != null)
{
//Page.RegisterStartupScript("message", "<script>alert('" + Session["src"].ToString() + "');</script>");
comp.Cidcard = Session["src"].ToString();
}
else
{
Page.RegisterStartupScript("message", "<script>alert('您获取的session值为空!');</script>");
}
comp.UID = ViewState["uid"].ToString();
if (ViewState["cid"] != null)
{
if (CompanyServices.Update(comp))
{
Bind(Convert.ToInt32(ViewState["cid"]));
Page.RegisterStartupScript("message", "<script>alert('更新成功!'); </script>");
}
else
{
Page.RegisterStartupScript("message", "<script>alert('操作失败!');</script>");
return;
}
}
else
{
if (CompanyServices.Insert(comp))
{
Page.RegisterStartupScript("message", "<script>alert('添加成功!');</script>");
}
else
{
Page.RegisterStartupScript("message", "<script>alert('操作失败!');</script>");
return;
}
}
}
catch (Exception ex)
{
Page.RegisterStartupScript("message", "<script>alert('" + ex.Message + "');</script>");
}
}
protected void Button2_Click(object sender, EventArgs e)
{
try
{
Company comp = new Company();
if (ViewState["cid"] != null)
{
comp = CompanyServices.GetByID(Convert.ToInt32(ViewState["cid"]));
}
else
{
comp = new Model.Company();
}
if (Session["src"] != null)
{
//Page.RegisterStartupScript("message", "<script>alert('" + Session["src"].ToString() + "');</script>");
comp.Ccode = Session["src"].ToString();
}
else
{
Page.RegisterStartupScript("message", "<script>alert('您获取的session值为空!');</script>");
}
comp.UID = ViewState["uid"].ToString();
if (ViewState["cid"] != null)
{
if (CompanyServices.Update(comp))
{
Bind(Convert.ToInt32(ViewState["cid"]));
Page.RegisterStartupScript("message", "<script>alert('更新成功!'); </script>");
}
else
{
Page.RegisterStartupScript("message", "<script>alert('操作失败!');</script>");
return;
}
}
else
{
if (CompanyServices.Insert(comp))
{
Page.RegisterStartupScript("message", "<script>alert('添加成功!');</script>");
}
else
{
Page.RegisterStartupScript("message", "<script>alert('操作失败!');</script>");
return;
}
}
}
catch (Exception ex)
{
Page.RegisterStartupScript("message", "<script>alert('" + ex.Message + "');</script>");
}
}
}
5、显示到网页 在IDCardInfo.aspx.cs中
Bind(Convert.ToInt32(ViewState["cid"]));
6、完成上边的会出现问题3的bug,需要在Global.asax中添加
void Application_BeginRequest(object sender, EventArgs e)
{
//HttpContext.Current.Request;
// HttpContext.Current.Response;
try
{
string session_param_name = "ASPSESSID";
string session_cookie_name = "ASP.NET_SESSIONID";
if (HttpContext.Current.Request.Form[session_param_name] != null)
{
UpdateCookie(session_cookie_name, HttpContext.Current.Request.Form[session_param_name]);
}
else if (HttpContext.Current.Request.QueryString[session_param_name] != null)
{
UpdateCookie(session_cookie_name, HttpContext.Current.Request.QueryString[session_param_name]);
}
}
catch (Exception)
{
HttpContext.Current.Response.StatusCode = 500;
HttpContext.Current.Response.Write("Error Initializing Session");
}
}
static void UpdateCookie(string cookie_name, string cookie_value)
{
HttpCookie cookie = HttpContext.Current.Request.Cookies.Get(cookie_name);
if (cookie == null)
{
cookie = new HttpCookie(cookie_name);
//SWFUpload 的Demo中给的代码有问题,需要加上cookie.Expires 设置才可以
cookie.Expires = DateTime.Now.AddYears(1);
HttpContext.Current.Request.Cookies.Add(cookie);
}
cookie.Value = cookie_value;
HttpContext.Current.Request.Cookies.Set(cookie);
}
因为SWFUpload是靠Flash进行上传的, Flash在IE下会把当前页面的Cookie发到Upload.ashx,但是Chrome、Firefox下则不会把当前页面的Cookie发到Upload.ashx。因为 Session是靠Cookie中保存的SessionId实现的,这样由于当前页面的Cookie不会传递给Flash请求的Upload.ashx,因此请求的文件发送到Upload.ashx就是一个新的Session了,当然这个Session就是没有登录的了。解决这个问题的思路也很简单,那就是手动把SessionId传递给服务器,再服务器端读出SessionId再加载Session。
因为在IDCardInfo.aspx中已经
post_params : {
"ASPSESSID" : "<%=Session.SessionID %>"
},
所以直接在Global.asax添加上边的代码就可以解决!!!!!!!!!!