//前台代码
<%@ page language="c#" autoeventwireup="true" codefile="test.aspx.cs" inherits="test" %>
<!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>无标题页</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:fileupload id="fileupload1" runat="server" cssclass="input3" width="290px"/>
<asp:button id="button1" runat="server" text="上传图片并创建文件夹" onclick="button1_click" />
</div>
</form>
</body>
</html>
//后台代码
using system;
using system.data;
using system.configuration;
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 system.io;
public partial class test : system.web.ui.page
{
protected void page_load(object sender, eventargs e)
{
}
protected void button1_click(object sender, eventargs e)
{
string uploadfilename, uploadfilelastname;
uploadfilename = fileupload1.postedfile.filename;//文件在本地的原始位置
uploadfilelastname = uploadfilename.substring(uploadfilename.lastindexof(".") + 1);//得到文件的扩展名
random rd = new random();//产生随机数
int valationno = 10 + rd.next(99);//产生随机数
string suiji = valationno.tostring();//产生随机数
string uploadfiletime = datetime.now.tostring("yyyymmddhhmmss") + suiji;//得到系统时间并加上随机数以便生成上传图片名称
string newuploadfilename = uploadfiletime + "." + uploadfilelastname;//产生上传图片的名称
string userdirectory = "testfile";//所要创建文件夹的名字,实际运用中可为用户注册id
string userpath = server.mappath("uploadfiles").tostring() + "//" + userdirectory + "//" + "productsimages";
if (!directory.exists(userpath)) //如果文件夹不存在则创建
{
directory.createdirectory(userpath);
}
fileupload1.postedfile.saveas(newuploadpahtname);//用保存的方法将图片上载
string suser_productsimageurl = "uploadfiles/" + userdirectory + "/" + "productsimages/" + newuploadfilename;//得到服务端图片的虚拟路径
//response.write(suser_productsimageurl);
}
}
新闻热点
疑难解答
图片精选