Tips: fileUploader为上传文件服务器控件名称
后台
1 相关属性和对象
HttpPostedFile file = this.fileUploader.PostedFile; //获取文件对象
string fileName = file.FileName;//文件名称
string fileExtension = System.IO.Path.GetExtension(fileName).ToLower(); //文件后缀名称
file.ContentLength //文件大小
file.SaveAs(url)//保存文件 ,url为路径(包括文件名称)
2删除文件
File.Exists(url) //检测路径是否存在 url为路径
File.Delete(url); //删除文件 url为路径
前台(js)
方法1:
var filePath = $("input[id*='fileUploader']").val(); //获取文件路径
if (filePath == "") { return false; }
var fso = new ActiveXObject('Scripting.FileSystemObject'); //创建文件对象(此方法需要将网站添加至信任站点,不可取)
var file = fso.GetFile(filePath);
var size= file.Size;//文件大小
var fileName = file.Name.toString(); //文件名
//将得到的文件名赋值给文本框
var lastName = new String(fileName).substring(0, fileName.lastIndexOf("."));
$("#<%=FileName.ClientID %>").val(lastName);
方法2
var filePath = $("input[id*='fileUploader']").val();
//用\将文件名解析
var fileNames = filePath.split("\\");
var length = fileNames.length;
//最后的就是文件名了
var fileName = fileNames[length - 1].toString();
//将得到的文件名赋值给文本框
var lastName = new String(fileName).substring(0, fileName.lastIndexOf("."));
$("#<%=FileName.ClientID %>").val(lastName);
文件下载
string FilesID = context.Request["FilesID"]; //获取文件信息ID
if (string.IsNullOrEmpty(FilesID)) //检测是否存在文件信息
{
Alert(context, "文件信息错误,下载失败!");
return;
}
var entity = _service.GetFilesInfo(new Guid(FilesID));
if (entity == null)
{
Alert(context, "不存在文件信息!");
return;
}
FileInfo DownloadFile = new FileInfo(entity.FileURL);
if (!DownloadFile.Exists) //检测文件路径是否存在
{
Alert(context, "指定路径的文件不存在!");
return;
}
string tempFileName = (entity.FileName + entity.FileExtName).Replace(" ",""); //得到名件名称,如文件名称中有空格去掉空格
context.Response.Clear();
context.Response.ClearHeaders();
context.Response.Buffer = false;
context.Response.ContentType = "application/octet-stream";
context.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(tempFileName, System.Text.Encoding.UTF8)); //弹出的文件 名称
context.Response.AppendHeader("Content-Length", DownloadFile.Length.ToString());
context.Response.WriteFile(DownloadFile.FullName);//DownloadFile.FullName保存文件名
context.Response.Flush();
context.Response.End();
//具体方法
private static void Alert(HttpContext context, string info)
{
context.Response.ContentType = "text/html";
context.Response.Write("<html><head><script>window.alert('" + info + "');window.opener=null;window.open('','_self');window.close();</script></head><body></body></html>");
context.Response.Flush();
context.Response.End();
}