C#_上传文件到服务器的temp文件夹

发布时间 2023-05-05 13:53:12作者: AutomationAnywhere

C#_上传文件到服务器的temp文件夹

  1. 写在*.aspx中  

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="有效代码_上传文件到服务器的temp文件夹.aspx.cs" Inherits="web_page_ssc_上传文件到服务器的temp文件夹" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>            
            <asp:FileUpload ID="fileUpload" runat="server" />
            <asp:Button ID="btnUpload" runat="server" OnClick="btnUpload_Click" Text="上传" />
            <asp:Literal ID="literal" runat="server"></asp:Literal>
        </div>
    </form>
</body>
</html>

 

  2. 写在*.aspx.cs中

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class web_page_ssc_上传文件到服务器的temp文件夹 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnUpload_Click(object sender, EventArgs e)
    {
        //判断是否上传了文件
        if (fileUpload.HasFile)
        {
            //指定上传文件在服务器上的保存路径
            string savePath = Server.MapPath("~/temp/");
            //检查服务器上是否存在这个物理路径,如果不存在则创建
            if (!System.IO.Directory.Exists(savePath))
            {
                //需要注意的是,需要对这个物理路径有足够的权限,否则会报错
                //另外,这个路径应该是在网站之下,而将网站部署在C盘却把文件保存在D盘
                System.IO.Directory.CreateDirectory(savePath);
            }
            savePath = savePath + "\\" + fileUpload.FileName;
            fileUpload.SaveAs(savePath);//保存文件
                                        //不过需要注意的是,在客户端访问却需要指定的是URL地址,而不是服务器上的物理地址
            literal.Text = string.Format("<a href='temp/{0}'>temp{0}</a>", fileUpload.FileName);
        }
    }
    
}