net上传文件并创建文件夹

本文介绍了一个ASP.NET中文件上传的基本实现方法,包括检查文件类型、创建年份文件夹及保存文件等步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

ExpandedBlockStart.gif代码
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 _Default : System.Web.UI.Page 
{
    
protected void Page_Load(object sender, EventArgs e)
    {

    }
    
/// <summary>
    
/// 上传文件到指定的文件夹
    
/// </summary>
    
/// <param name="sender"></param>
    
/// <param name="e"></param>
    protected void btnSure_Click(object sender, EventArgs e)
    {
        
//string phName = this.txtName.Text;
        
//string phType = this.ddlType.SelectedValue;

        
if (this.myFile.PostedFile != null)  //myFile是上传控件的名称
        {
            
string photoName1 = myFile.PostedFile.FileName; //获取初始文件名
            int i = photoName1.LastIndexOf("."); //取得文件名中最后一个"."的索引
            string newext = photoName1.Substring(i); //获取文件扩展名
            if (newext != ".gif" && newext != ".jpg" && newext != ".jpeg" && newext != ".bmp" && newext != ".png")
            {
                Response.Write(
"文件格式不正确!");
                Response.End();
            }
            DateTime now 
= DateTime.Now; //获取系统时间

            
string classid = DateTime.Now.Year.ToString();

            
//根据年份判断在该路径下是否存在以当年年份文件夹 否则将建立以该年份的文件夹
            if (!Directory.Exists(HttpContext.Current.Server.MapPath("photos/"+ "\\" + classid))                //HttpContext.Current.Server.MapPath(相对路径):把相对路径转为服务器上的绝对路径。 File.Exists(绝对路径):检查是否存在绝对路径指向的文件或目录。
            {
                System.IO.Directory.CreateDirectory(@HttpContext.Current.Server.MapPath(
"photos/"+ "\\" + classid);              //System.IO.Directory.CreateDirectory(文件夹绝对路径):建立绝对路径文件夹。
            }
            
string photoName2 = now.Millisecond.ToString() + "_" + myFile.PostedFile.ContentLength.ToString() + newext; //重新为文件命名,时间毫秒部分+文件大小+扩展名
            myFile.PostedFile.SaveAs(Server.MapPath("photos\\"+classid+"\\" + photoName2)); // 保存文件到路径,用Server.MapPath()取当前文件的绝对目录.在asp.net里"\"必须用"\\"代替
        }

    }

 

转载于:https://www.cnblogs.com/ming5536/archive/2010/12/17/1909425.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值