//前臺代碼
<%@ 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() + "http://" + userdirectory + "http://" + "productsimages";
if (!directory.exists(userpath)) //如果文件夾不存在則創建
{
directory.createdirectory(userpath);
}
fileupload1.postedfile.saveas(newuploadpahtname);//用保存的方法將圖片上載
string suser_productsimageurl = "uploadfiles/" + userdirectory + "/" + "productsimages/" + newuploadfilename;//得到服務端圖片的虛擬路徑
//response.write(suser_productsimageurl);
}
}
新聞熱點
疑難解答
圖片精選