ASP.NET文件上传

<asp:FileUpload ID="FileUpload" runat="server" />
private string upLoad() {
        string path="";
        
        string filepath = FileUpload.PostedFile.FileName;
        string fileName = filepath.Substring(filepath.LastIndexOf("\") + 1);
        path = Server.MapPath(@"~/files/") + filepath;
        string filePath = "~/files/" + fileName;
        Response.Write(filePath);
        FileUpload.SaveAs(path);

        return filePath;
    }

第二种方法,大致是一样的

protected void btnUpload_Click(object sender, EventArgs e)
{
    if (FileUpload1.HasFile)
    {
        string fileExt = System.IO.Path.GetExtension(FileUpload1.FileName);
        if (fileExt == ".jpg" || fileExt == ".gif")
        {
            try
            {
                FileUpload1.SaveAs(Server.MapPath("/ScenicImg")+"\" + FileUpload1.FileName);
                Label1.Text = "客户端路径:" + FileUpload1.PostedFile.FileName + "<br>" +
                              "文件名:" + System.IO.Path.GetFileName(FileUpload1.FileName) + "<br>" +
                              "文件扩展名:" + System.IO.Path.GetExtension(FileUpload1.FileName) + "<br>" +
                              "文件大小:" + FileUpload1.PostedFile.ContentLength + " KB<br>" +
                              "文件MIME类型:" + FileUpload1.PostedFile.ContentType + "<br>" +
                              "保存路径:" + Server.MapPath("/ScenicImg") + "\" + FileUpload1.FileName;
            }
            catch (Exception ex)
            {
                Label1.Text = "发生错误:" + ex.Message.ToString();
            }
        }
        else
        {
            Label1.Text = "只允许上传jpg、gif文件!";
        }
    }
    else
    {
        Label1.Text = "没有选择要上传的文件!";
    }
}
原文地址:https://www.cnblogs.com/zhao123/p/3436654.html