文件上传与下载
protected void Button1_Click(object sender, EventArgs e)
{
}
/// <summary>
/// 上传文件 返回空为没有文件,返回0为格式错误!
/// </summary>
/// <returns></returns>
private string UploadFile()
{
string directoryPath = "";
string folderDate = "";
string month = "";
string day = "";
string fileName = "";
string fileNameLast = "";
string saveAddr = "";
if (DateTime.Now.Month < 10)
{ month = "0" + DateTime.Now.Month; }
else
{ month = Convert.ToString(DateTime.Now.Month); }
if (DateTime.Now.Day < 10)
{ day = "0" + DateTime.Now.Day; }
else
{ day = Convert.ToString(DateTime.Now.Day); }
folderDate = DateTime.Now.Year + "" + month + "" + day;
if ((FileUpload1.PostedFile != null) && (FileUpload1.PostedFile.ContentLength > 0))
{
fileName = System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName);
fileNameLast = fileName.Substring(fileName.Length - 4, 4).ToLowerInvariant();
if (!fileNameLast.Contains("zip") && !fileNameLast.Contains("txt") && !fileNameLast.Contains("rar") && !fileNameLast.Contains("doc"))
{
return "0";//文件格式错误!
}
Random r = new Random();
fileName = Convert.ToString(r.Next(10000000, 99999999)) + fileNameLast;
directoryPath = Server.MapPath("../file/" + folderDate + "/");
if (Directory.Exists(directoryPath))//文件夹是否存在
{
saveAddr = Server.MapPath("../file/" + folderDate + "/") + fileName;
FileUpload1.PostedFile.SaveAs(saveAddr);
}
else
{
Directory.CreateDirectory(directoryPath);
saveAddr = Server.MapPath("../file/" + folderDate + "/") + fileName;
FileUpload1.PostedFile.SaveAs(saveAddr);
}
}
else
{
return "";
}
return "Images/" + folderDate + "/" + fileName;
}
大家帮忙看下,那个上传按钮里应该怎么写?先谢谢了,很急,在线等,希望各位高手帮帮忙!
------解决方案--------------------
string rst=UploadFile();
就可以了啥
------解决方案--------------------
if (fileUpload.HasFile)
{
string savePath = Server.MapPath("~/upload/");
if (!System.IO.Directory.Exists(savePath))
{
System.IO.Directory.CreateDirectory(savePath);
}
savePath = savePath + "\\" + fileUpload.FileName;
fileUpload.SaveAs(savePath);//保存文件
}
path.GetExtention判断文件格式
下载response.writefile