如何实现图片上传功能??--100分 我想实现个图片上传功能,能存储在指定的文件夹中,并且能对上传的图片进行自动改名,改成2005091600000.jpeg,并能自动增加,那位高手帮忙解决下!!! 解决方案 » 免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货 http://dotnet.aspx.cc/ShowDetail.aspx?id=58EA3515-36F2-4FD9-AC89-EAF49F59816C自动改名,可以用当前日前的年月日和时间为名字 <script> function checkFiles() { if (Form1.file.value=="") { alert("请选择图片!"); return false; } var type=Form1.file.value.match(/^(.*)(\.)(.{1,8})$/)[3]; type=type.toUpperCase(); if(type=="GIF" || type=="JPG" || type=="PNG") { return true; } else { alert("上传类型有误,请检查文件格式是否正确!"); return false; } } </script><TR> <TD></TD> <TD><INPUT id="file" type="file" name="file" runat="server"><FONT face="宋体"> <asp:button id="BtnSure" runat="server" Text="上传"></asp:button> <asp:Label id="Label1" runat="server"></asp:Label></FONT></TD> <TD></TD> </TR> private void Page_Load(object sender, System.EventArgs e) { // 在此处放置用户代码以初始化页面 Response.Buffer = true; Response.ExpiresAbsolute = DateTime.Now.AddDays(-1); Response.Cache.SetExpires(DateTime.Now.AddDays(-1)); Response.Expires = 0; Response.CacheControl = "no-cache"; Response.Cache.SetNoStore(); if (!IsPostBack) { BtnSure.Attributes.Add("onclick","return checkFiles();"); BtnClose.Attributes.Add("onclick","window.close();return false"); } } private void BtnSure_Click(object sender, System.EventArgs e) { //获得文件后缀名 string fileName = file.PostedFile.FileName; string fileExcep = fileName.Substring(fileName.LastIndexOf(".")+1); //新的文件名 string newFileName = System.DateTime.Now.ToString("yyyyMMddhhmmss"); newFileName += "."+fileExcep; //上传文件 try { file.PostedFile.SaveAs(Server.MapPath("uploadfiles\\"+newFileName)); //关闭窗口并返回上传的文件名 string strScript = "<script>\n"; strScript += "window.parent.returnValue = '"+newFileName+"';\n"; strScript += "window.parent.close();\n"; strScript += "</script>\n"; Page.RegisterStartupScript("goBack",strScript); //Response.Write(strScript); Label1.Text = strScript; } catch(Exception Ex1) { Response.Write("error:"+Ex1.ToString()); } } 给你贴段我写的代码:aspx页面:<INPUT type="file" id="UploadFile" runat="server" NAME="UploadFile"><asp:Button id="Button1" runat="server" Text="上传" CausesValidation="False"></asp:Button><asp:Label id="uploaderror" runat="server" ForeColor="Red"></asp:Label>CS页面:命名空间如下(可能有你用不着的命名空间):using System;using System.Collections;using System.ComponentModel;using System.Data;using System.Data.SqlClient;using System.Drawing;using System.Web;using System.Web.SessionState;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.UI.HtmlControls;using System.IO;using System.Drawing.Imaging;具体实现函数如下:private void Button1_Click(object sender, System.EventArgs e) { string PicExtension=".jpg|.gif|.png|.bmp";//定义允许的图片扩展名 if (!(UploadFile.PostedFile.ContentLength>0)) { uploaderror.Text="您没有选择上传文件"; } else { string fileName,fileExtension; //取得上传的文件名 fileName=Path.GetFileName(UploadFile.PostedFile.FileName); //取得文件扩展名 fileExtension=System.IO.Path.GetExtension(fileName); //定义图片宽度和高度限制 int PicWidth=180,PicHeight=180; string result=PicExtension.Replace(fileExtension,""); if (PicExtension!=result) { string imgPath=UploadFile.PostedFile.FileName; System.Drawing.Image image=System.Drawing.Image.FromFile(imgPath); //使用Image对象的Height and Width属性取得图片的高度和宽度 float A,B; int newwidth=image.Width,newheight=image.Height; A=(float)image.Width/(float)PicWidth; B=(float)image.Height/(float)PicHeight; if (A>1 || B>1)//按照等比缩放 { if(A>B) { newwidth=PicWidth; newheight=PicHeight*image.Height/image.Width; } else { newwidth=PicWidth*image.Width/image.Height; newheight=PicHeight; } } System.Drawing.Image.GetThumbnailImageAbort callb=null; System.Drawing.Image newimage=image.GetThumbnailImage(newwidth,newheight,callb,new System.IntPtr()); //对图片进行按年月日小时分秒微秒重新命名 string SaveFileName=DateTime.Now.Year.ToString()+DateTime.Now.Month.ToString() +DateTime.Now.Day.ToString()+DateTime.Now.Hour.ToString() +DateTime.Now.Minute.ToString()+DateTime.Now.Second.ToString() +DateTime.Now.Millisecond.ToString(); //创建随机数对象 Random rnd=new Random(); //调用Next方法产生随机数 SaveFileName+=rnd.Next(1,100000).ToString(); string UploadDir;//定义存放图片的文件夹 UploadDir="CompanyProduct"; if (Directory.Exists(Server.MapPath("UploadFiles"))==false) { Directory.CreateDirectory(Server.MapPath("UploadFiles")); } if (Directory.Exists(Server.MapPath("UploadFiles/"+UploadDir))==false) { Directory.CreateDirectory(Server.MapPath("UploadFiles/"+UploadDir)); } string SavePath="UploadFiles/"+UploadDir+"/"+SaveFileName+fileExtension; newimage.Save(Server.MapPath(SavePath)); newimage.Dispose(); image.Dispose(); uploaderror.Text="上传成功"; } else { uploaderror.Text="您上传的文件不是图片"; } }上面的函数主要是实现将图片上传到uploadfiles文件夹下的自定义文件夹中,并按照按年月日小时分秒微秒重新命名,同时可以实现图片宽度和高度超过指定大小时的压缩 'guid类型 网卡mac地址+cpu时钟,所以文件绝对唯一Dim FileName As String = Guid.NewGuid().ToString() + "." + FileExt'上传的服务器地址Dim SrvFileName As String = Server.MapPath("/UpLoadFiles") + "/" + FileName'FileUp是 HtmlInputFile 控件<INPUT id="FileUp" type="file" runat="server">FileUp.PostedFile.SaveAs(SrvFileName) 参考http://dev.csdn.net/develop/article/22/22114.shtm 文件上传很简单,.net中有现成的类专干这事,在MSDN里把相关类熟悉一下,很快就能搞定.但一些特殊要求比如批量上传,带即时进度条的上传等这些无现成方法的功能实现起来就有一定难度了. 用File进行操作前台添加:<INPUT type="file" size="22" name="UpFile" runat="server" id="UpFile">后台执行上传Dim upFilePath As StringupFilePath = MapPath("/") & "200511111.jpg"UpFile.PostedFile.SaveAs(upFilePath) 我最近开发项目都是用以上方法,很简便,你可以试一下上传不大于4M的就可以。如果大于的,要在CONFIG里面加:------------------------------------------------------------<!--指示 ASP.NET 支持的HTTP方式上载的最大字节数。 指定的大小以 KB 为单位。 默认值为 4096 KB (4 MB)。改成10240(10M) --> <httpRuntime executionTimeout="600" maxRequestLength="10240" useFullyQualifiedRedirectUrl="false" minFreeThreads="8" minLocalRequestFreeThreads="4" appRequestQueueLimit="100" enableVersionHeader="true"/> wxl_pilot(空军飞行员)的不错,比较周到,呵呵 图片太大,导致页面卡如何解决? for循环嵌套问题。大家帮我看下,在线等 js触发onchange事件,为什么原有页面的内容全部消失了? 各位高手:如何实现DataList隔行显示不同颜色? 非高手勿请:奇怪的未将对象引用设置到对象的实例 请教哪个数据控件可以将数据按所需格式输出? 求教各位高手,我遇到的是什么问题啊? asp.net程序员的酬薪调查 在线等~~~~ DataGrid添加列的问题? 我的.net程序运行不起来---在线等 头疼了一周的问题:ASP.NET如何从前端页面代码中获取后置代码的变量值?
自动改名,可以用当前日前的年月日和时间为名字
function checkFiles()
{
if (Form1.file.value=="")
{
alert("请选择图片!");
return false;
}
var type=Form1.file.value.match(/^(.*)(\.)(.{1,8})$/)[3]; type=type.toUpperCase();
if(type=="GIF" || type=="JPG" || type=="PNG")
{
return true;
}
else
{
alert("上传类型有误,请检查文件格式是否正确!");
return false;
} }
</script>
<TR>
<TD></TD>
<TD><INPUT id="file" type="file" name="file" runat="server"><FONT face="宋体">
<asp:button id="BtnSure" runat="server" Text="上传"></asp:button>
<asp:Label id="Label1" runat="server"></asp:Label></FONT></TD>
<TD></TD>
</TR>
private void Page_Load(object sender, System.EventArgs e)
{
// 在此处放置用户代码以初始化页面
Response.Buffer = true;
Response.ExpiresAbsolute = DateTime.Now.AddDays(-1);
Response.Cache.SetExpires(DateTime.Now.AddDays(-1));
Response.Expires = 0;
Response.CacheControl = "no-cache";
Response.Cache.SetNoStore();
if (!IsPostBack)
{
BtnSure.Attributes.Add("onclick","return checkFiles();");
BtnClose.Attributes.Add("onclick","window.close();return false");
}
}
private void BtnSure_Click(object sender, System.EventArgs e)
{
//获得文件后缀名
string fileName = file.PostedFile.FileName;
string fileExcep = fileName.Substring(fileName.LastIndexOf(".")+1);
//新的文件名
string newFileName = System.DateTime.Now.ToString("yyyyMMddhhmmss");
newFileName += "."+fileExcep;
//上传文件
try
{
file.PostedFile.SaveAs(Server.MapPath("uploadfiles\\"+newFileName));
//关闭窗口并返回上传的文件名
string strScript = "<script>\n";
strScript += "window.parent.returnValue = '"+newFileName+"';\n";
strScript += "window.parent.close();\n";
strScript += "</script>\n";
Page.RegisterStartupScript("goBack",strScript);
//Response.Write(strScript);
Label1.Text = strScript;
}
catch(Exception Ex1)
{
Response.Write("error:"+Ex1.ToString());
}
}
aspx页面:
<INPUT type="file" id="UploadFile" runat="server" NAME="UploadFile">
<asp:Button id="Button1" runat="server" Text="上传" CausesValidation="False"></asp:Button>
<asp:Label id="uploaderror" runat="server" ForeColor="Red"></asp:Label>
CS页面:
命名空间如下(可能有你用不着的命名空间):
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Drawing.Imaging;具体实现函数如下:
private void Button1_Click(object sender, System.EventArgs e)
{
string PicExtension=".jpg|.gif|.png|.bmp";//定义允许的图片扩展名
if (!(UploadFile.PostedFile.ContentLength>0))
{
uploaderror.Text="您没有选择上传文件";
}
else
{
string fileName,fileExtension;
//取得上传的文件名
fileName=Path.GetFileName(UploadFile.PostedFile.FileName);
//取得文件扩展名
fileExtension=System.IO.Path.GetExtension(fileName);
//定义图片宽度和高度限制
int PicWidth=180,PicHeight=180;
string result=PicExtension.Replace(fileExtension,"");
if (PicExtension!=result)
{
string imgPath=UploadFile.PostedFile.FileName;
System.Drawing.Image image=System.Drawing.Image.FromFile(imgPath);
//使用Image对象的Height and Width属性取得图片的高度和宽度
float A,B;
int newwidth=image.Width,newheight=image.Height;
A=(float)image.Width/(float)PicWidth;
B=(float)image.Height/(float)PicHeight;
if (A>1 || B>1)//按照等比缩放
{
if(A>B)
{
newwidth=PicWidth;
newheight=PicHeight*image.Height/image.Width;
}
else
{
newwidth=PicWidth*image.Width/image.Height;
newheight=PicHeight;
}
}
System.Drawing.Image.GetThumbnailImageAbort callb=null;
System.Drawing.Image newimage=image.GetThumbnailImage(newwidth,newheight,callb,new System.IntPtr());
//对图片进行按年月日小时分秒微秒重新命名
string SaveFileName=DateTime.Now.Year.ToString()+DateTime.Now.Month.ToString()
+DateTime.Now.Day.ToString()+DateTime.Now.Hour.ToString()
+DateTime.Now.Minute.ToString()+DateTime.Now.Second.ToString()
+DateTime.Now.Millisecond.ToString();
//创建随机数对象
Random rnd=new Random();
//调用Next方法产生随机数
SaveFileName+=rnd.Next(1,100000).ToString();
string UploadDir;//定义存放图片的文件夹
UploadDir="CompanyProduct"; if (Directory.Exists(Server.MapPath("UploadFiles"))==false)
{
Directory.CreateDirectory(Server.MapPath("UploadFiles"));
}
if (Directory.Exists(Server.MapPath("UploadFiles/"+UploadDir))==false)
{
Directory.CreateDirectory(Server.MapPath("UploadFiles/"+UploadDir));
}
string SavePath="UploadFiles/"+UploadDir+"/"+SaveFileName+fileExtension;
newimage.Save(Server.MapPath(SavePath));
newimage.Dispose();
image.Dispose();
uploaderror.Text="上传成功";
}
else
{
uploaderror.Text="您上传的文件不是图片";
}
}上面的函数主要是实现将图片上传到uploadfiles文件夹下的自定义文件夹中,并按照按年月日小时分秒微秒重新命名,同时可以实现图片宽度和高度超过指定大小时的压缩
Dim FileName As String = Guid.NewGuid().ToString() + "." + FileExt
'上传的服务器地址
Dim SrvFileName As String = Server.MapPath("/UpLoadFiles") + "/" + FileName
'FileUp是 HtmlInputFile 控件<INPUT id="FileUp" type="file" runat="server">
FileUp.PostedFile.SaveAs(SrvFileName)
前台添加:
<INPUT type="file" size="22" name="UpFile" runat="server" id="UpFile">后台执行上传
Dim upFilePath As String
upFilePath = MapPath("/") & "200511111.jpg"
UpFile.PostedFile.SaveAs(upFilePath)
上传不大于4M的就可以。如果大于的,要在CONFIG里面加:
------------------------------------------------------------
<!--指示 ASP.NET 支持的HTTP方式上载的最大字节数。
指定的大小以 KB 为单位。
默认值为 4096 KB (4 MB)。改成10240(10M)
-->
<httpRuntime executionTimeout="600" maxRequestLength="10240" useFullyQualifiedRedirectUrl="false" minFreeThreads="8" minLocalRequestFreeThreads="4" appRequestQueueLimit="100" enableVersionHeader="true"/>