1. 程式人生 > >html加C#上傳文件

html加C#上傳文件

eat 服務器 request har directory org ont exist 文件流

最近在學上傳文件部分內容,包括創建文件夾,設置文件夾屬性,上傳文件並保存。

前臺代碼:

<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 runat="server" id="form1" method="post" enctype="multipart/form-data">

<input name="f" type="file" />

<input name="s" type="submit" />

</form>

</body>

</html>

後臺代碼:

System.Web.HttpFileCollection _file = System.Web.HttpContext.Current.Request.Files;

if (_file.Count > 0)

{

//文件大小

long size = _file[0].ContentLength;

//文件類型

string type = _file[0].ContentType;

//文件名

string name = _file[0].FileName;

//文件格式

string _tp = System.IO.Path.GetExtension(name);

if (_tp.ToLower() == ".jpg" || _tp.ToLower() == ".jpeg" || _tp.ToLower() == ".gif" || _tp.ToLower() == ".png" || _tp.ToLower() == ".swf")

{

//獲取文件流

System.IO.Stream stream = _file[0].InputStream;

//保存文件

string saveName = DateTime.Now.ToString("yyyyMMddHHmmss") + _tp;

string path = Server.MapPath("") + "/upload/area/" + saveName;

_file[0].SaveAs(path);

}

}

後來想到,如何判斷文件夾是否存在呢?如果不存在就直接保存就會出錯,或者已經存在的話,會不會覆蓋掉?

使用如下方法,判斷是否存在,不存在則創建

if (!Directory.Exists(sPath))
  {
   Directory.CreateDirectory(sPath);

  }

//後來創建了文件夾,還是報路徑錯誤,原因猜想:1,沒有包含在項目中。2,沒有權限。

解決方法:

1,手動將其包含在項目中就可以了,確實可以解決,但是非常不爽,因為程序運行在服務器上,你不可能程序創建了文件夾,然後手動去把他再加進項目中吧。

2,網上查說是創建的文件夾為只讀屬性了,但是我手動把程序創建的文件夾屬性只讀去掉,還是不成功,但是使用下面的代碼將文件夾屬性“只讀”去掉,上傳就成功了。

去除文件夾的只讀屬性: System.IO.DirectoryInfo DirInfo = new DirectoryInfo(“filepath”);
     DirInfo.Attributes = FileAttributes.Normal & FileAttributes.Directory;

去除文件的只讀屬性:  System.IO.File.SetAttributes("filepath", System.IO.FileAttributes.Normal);

於是結束後,將新建文件夾部分代碼重新整理了一下,變成了:

string _tp = System.IO.Path.GetExtension(name);

if (_tp.ToLower() == ".jpg" || _tp.ToLower() == ".jpeg" || _tp.ToLower() == ".gif" || _tp.ToLower() == ".png" || _tp.ToLower() == ".swf")
{

string saveName = DateTime.Now.ToString("yyyyMMddHHmmss") + _tp;
string file = "/" + DateTime.Now.ToString("yyyyMMdd")+"/";
string path = Server.MapPath("~")+file;

if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
DirectoryInfo dirInfo = new DirectoryInfo(path);
dirInfo.Attributes = FileAttributes.Normal&FileAttributes.Directory;
}
_file[0].SaveAs(path+saveName);
ViewBag.imgPath = file + saveName;//可以保存至數據庫或者xml等其他地方,我這裏是測試,直接返回到前臺了

}

html加C#上傳文件