private long ChunkSize = 102400;//100K 每次读取文件,只读取100K,这样可以缓解服务器的压力 public void ProcessRequest(HttpContext context) { //\SMT\OA\考勤管理\2010121702324784503941.JPG //string fileName = "123.jpg";//客户端保存的文件名 if (context.Request.QueryString["filename"] == null) { return; } String fileurl = HttpUtility.UrlDecode(context.Request.QueryString["filename"]); // string filePath = string.Format(SavePath, fileName.Split('|')[0], fileName.Split('|')[1], fileName.Split('|')[2]+"\\"+fileName.Split('|')[3]); //context.Server.MapPath("Bubble.jpg"); string filePath = string.Format(FileConfig.GetCompanyItem(fileurl.Split('\\')[1]).SavePath, fileurl.Split('\\')[1], fileurl.Split('\\')[2], fileurl.Split('\\')[3] + "\\" + fileurl.Split('\\')[4]); string saveFileName = fileurl.Split('\\')[5];//保存文件名 System.IO.FileInfo fileInfo = new System.IO.FileInfo(filePath); if (fileInfo.Exists == true) { byte[] buffer = new byte[ChunkSize]; context.Response.Clear(); System.IO.FileStream iStream = System.IO.File.OpenRead(filePath); long dataLengthToRead = iStream.Length;//获得下载文件的总大小 context.Response.ContentType = "application/octet-stream"; //通知浏览器下载文件而不是打开 context.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(saveFileName, System.Text.Encoding.UTF8)); while (dataLengthToRead > 0 && context.Response.IsClientConnected) { int lengthRead = iStream.Read(buffer, 0, Convert.ToInt32(ChunkSize));//读取的大小 context.Response.OutputStream.Write(buffer, 0, lengthRead); context.Response.Flush(); dataLengthToRead = dataLengthToRead - lengthRead; } iStream.Dispose(); iStream.Close(); context.Response.Close(); context.Response.End(); } else { System.Web.HttpContext.Current.Response.Write("<script>alert('该文件不存在!');</script>"); } //context.Response.ContentType = "text/plain"; //context.Response.Write("Hello World"); }
private long ChunkSize = 102400;//100K 每次读取文件,只读取100K,这样可以缓解服务器的压力 /// <summary> /// 下载文件 /// </summary> /// <param name="context"></param> public void ProcessRequest(HttpContext context) { SMT.Foundation.Log.Tracer.Debug("开始下载文件"); try { //\SMT\OA\考勤管理\2010121702324784503941.JPG //string fileName = "123.jpg";//客户端保存的文件名 if (context.Request.QueryString["filename"] == null) { return; } String fileurl = HttpUtility.UrlDecode(context.Request.QueryString["filename"]); SMT.Foundation.Log.Tracer.Debug("下载文件地址:" + fileurl); // string filePath = string.Format(SavePath, fileName.Split('|')[0], fileName.Split('|')[1], fileName.Split('|')[2]+"\\"+fileName.Split('|')[3]); //context.Server.MapPath("Bubble.jpg"); string filePath = string.Format(FileConfig.GetCompanyItem(fileurl.Split('\\')[1]).SavePath, fileurl.Split('\\')[1], fileurl.Split('\\')[2], fileurl.Split('\\')[3] + "\\" + fileurl.Split('\\')[4]); string NewfilePath = string.Format(FileConfig.GetCompanyItem(fileurl.Split('\\')[1]).SavePath, fileurl.Split('\\')[1], fileurl.Split('\\')[2], fileurl.Split('\\')[3] + "\\" + fileurl.Split('\\')[5]); string saveFileName = fileurl.Split('\\')[5]; //保存文件名 string StrServicesFileName = fileurl.Split('\\')[4].Substring(0, 8); //取前面的作为解密字符串 System.IO.FileInfo fileInfo = new System.IO.FileInfo(filePath); if (fileInfo.Exists == true) { //byte[] buffer = new byte[ChunkSize]; //context.Response.Clear(); //string Key = this.key; string Key = StrServicesFileName; //DESCryptoServiceProvider des = new DESCryptoServiceProvider(); //des.Key = ASCIIEncoding.Default.GetBytes(Key); //des.IV = ASCIIEncoding.Default.GetBytes(Key); ////Create a file stream to read the encrypted file back. //FileStream fsread = new FileStream(filePath, FileMode.Open,FileAccess.Read); ////Create a DES decryptor from the DES instance. //ICryptoTransform desdecrypt = des.CreateDecryptor(); //byte[] FileStreamArray = new byte[fsread.Length]; //fsread.Read(FileStreamArray, 0, FileStreamArray.Length); //MemoryStream ms = new MemoryStream(); //CryptoStream FileCryptoStream = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Read); //FileCryptoStream.Write(FileStreamArray, 0, FileStreamArray.Length); //FileCryptoStream.FlushFinalBlock(); //FileStream filOutStream = new FileStream(NewfilePath, FileMode.OpenOrCreate, FileAccess.Write); ////InputFileStream = File.OpenWrite(FileName); //foreach (byte b in ms.ToArray()) //{ // filOutStream.WriteByte(b); //} //fsread.Close(); //ms.Close(); //filOutStream.Close(); //filOutStream.Dispose(); CryptoHelp.DecryptFile(filePath, NewfilePath, StrServicesFileName); //System.IO.FileStream iStream = System.IO.File.OpenRead(NewfilePath); long dataToRead; int length; byte[] buffer = new Byte[300000]; System.IO.FileStream iStream = new System.IO.FileStream(NewfilePath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read); // Total bytes to read: dataToRead = iStream.Length; context.Response.ContentType = "application/octet-stream"; context.Response.Charset = "UTF-8"; context.Response.AddHeader("Content-Disposition", "attachment; filename=" + System.Web.HttpUtility.UrlEncode(saveFileName, System.Text.Encoding.UTF8)); // Read the bytes. while (dataToRead > 0) { // Verify that the client is connected. if (context.Response.IsClientConnected) { // Read the data in buffer. length = iStream.Read(buffer, 0, 300000); // Write the data to the current output stream. context.Response.OutputStream.Write(buffer, 0, length); // Flush the data to the HTML output. context.Response.Flush(); buffer = new Byte[300000]; dataToRead = dataToRead - length; } else { //prevent infinite loop if user disconnects dataToRead = -1; } } if (iStream != null) { //Close the file. iStream.Close(); } context.Response.Clear(); context.Response.End(); //long dataLengthToRead = iStream.Length;//获得下载文件的总大小 //context.Response.ContentType = "application/octet-stream"; ////通知浏览器下载文件而不是打开 //context.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(saveFileName, System.Text.Encoding.UTF8)); //while (dataLengthToRead > 0 && context.Response.IsClientConnected) //{ // int lengthRead = iStream.Read(buffer, 0, Convert.ToInt32(ChunkSize));//读取的大小 // context.Response.OutputStream.Write(buffer, 0, lengthRead); // //context.Response.Flush(); // dataLengthToRead = dataLengthToRead - lengthRead; //} //context.Response.Flush(); //iStream.Dispose(); //iStream.Close(); ////context.Response.Close(); //context.Response.Clear(); ////File.Delete(NewfilePath); //context.Response.End(); } else { System.Web.HttpContext.Current.Response.Write("<script>alert('该文件不存在!');</script>"); } //context.Response.ContentType = "text/plain"; //context.Response.Write("Hello World"); } catch (Exception ex) { SMT.Foundation.Log.Tracer.Debug("下载文件出错" + ex.ToString()); } }
protected void Page_Load(object sender, EventArgs e) { SMT.Foundation.Log.Tracer.Debug("开始下载文件"); try { //\SMT\OA\考勤管理\2010121702324784503941.JPG //string fileName = "123.jpg";//客户端保存的文件名 bool IsThum = false;//是否下载缩略图、不经过解密处理开关 if (Request["filename"] == null) { return; } if (Request["flag"] != null) { IsThum = true; } String fileurl = HttpUtility.UrlDecode(Request["filename"]); SMT.Foundation.Log.Tracer.Debug("下载文件地址:" + fileurl); string[] arrFilePath = fileurl.Split('\\'); // string filePath = string.Format(SavePath, fileName.Split('|')[0], fileName.Split('|')[1], fileName.Split('|')[2]+"\\"+fileName.Split('|')[3]); //context.Server.MapPath("Bubble.jpg"); string filePath = ""; if (arrFilePath.Length == 6) { filePath = string.Format(FileConfig.GetCompanyItem(arrFilePath[1]).SavePath, arrFilePath[1], arrFilePath[2], arrFilePath[3] + "\\" + arrFilePath[4]); } else { filePath = string.Format(FileConfig.GetCompanyItem(arrFilePath[1]).SavePath, arrFilePath[1], arrFilePath[2], arrFilePath[3] + "\\" + arrFilePath[4]) + "\\" + arrFilePath[arrFilePath.Length - 2]; } string NewfilePath = ""; if (!IsThum) { NewfilePath = string.Format(FileConfig.GetCompanyItem(arrFilePath[1]).SavePath, arrFilePath[1], arrFilePath[2], arrFilePath[3] + "\\" + arrFilePath[5]); } else { //缩略图没有进行加密操作所以还是显示原图 NewfilePath = string.Format(FileConfig.GetCompanyItem(arrFilePath[1]).SavePath, arrFilePath[1], arrFilePath[2], arrFilePath[3] + "\\" + arrFilePath[4]) + "\\" + arrFilePath[arrFilePath.Length - 2]; } SMT.Foundation.Log.Tracer.Debug("下载真实文件地址NewfilePath:" + NewfilePath); string saveFileName = arrFilePath[arrFilePath.Length - 1]; //获取文件名 string StrServicesFileName = arrFilePath[arrFilePath.Length - 2].Substring(0, 8); //取前面的作为解密字符串 System.IO.FileInfo fileInfo = new System.IO.FileInfo(filePath); if (fileInfo.Exists == true) { string Key = StrServicesFileName; if (!IsThum) { CryptoHelp.DecryptFile(filePath, NewfilePath, StrServicesFileName); } Response.Charset = "utf-8"; Response.ContentEncoding = System.Text.Encoding.UTF8; //ctx.Response.ContentEncoding Response.AppendHeader("Content-Type", "text/html;charset=utf-8"); Response.AppendHeader("Content-Disposition", string.Format("attachment; filename={0}", HttpUtility.UrlEncode(saveFileName, System.Text.Encoding.UTF8))); using (FileStream fs = new FileStream(NewfilePath, FileMode.Open, FileAccess.Read)) { SMT.Foundation.Log.Tracer.Debug("下载文件路径NewfilePath:" + NewfilePath); SMT.Foundation.Log.Tracer.Debug("下载文件大小:" + fs.Length); byte[] fileData = new byte[fs.Length]; int numBytesToRead = (int)fs.Length; int numBytesRead = 0; while (numBytesToRead > 0) { // Read may return anything from 0 to numBytesToRead. int n = fs.Read(fileData, numBytesRead, numBytesToRead); // Break when the end of the file is reached. if (n == 0) { break; } numBytesRead += n; numBytesToRead -= n; } fs.Close(); SMT.Foundation.Log.Tracer.Debug("下载文件地址fileData:" + fileData.Length); Response.BinaryWrite(fileData); } ////System.IO.FileStream iStream = System.IO.File.OpenRead(NewfilePath); //long dataToRead; //int length; //byte[] buffer = new Byte[300000]; //System.IO.FileStream iStream = new System.IO.FileStream(NewfilePath, System.IO.FileMode.Open, //System.IO.FileAccess.Read, System.IO.FileShare.Read); //// Total bytes to read: //dataToRead = iStream.Length; //Response.ContentType = "application/octet-stream"; //Response.Charset = "UTF-8"; //Response.AddHeader("Content-Disposition", "attachment; filename=" + System.Web.HttpUtility.UrlEncode(saveFileName, System.Text.Encoding.UTF8)); //Response.AddHeader("Content-Length", dataToRead.ToString()); //// Read the bytes. //while (dataToRead > 0) //{ // // Verify that the client is connected. // if (Response.IsClientConnected) // { // // Read the data in buffer. // length = iStream.Read(buffer, 0, 300000); // // Write the data to the current output stream. // Response.OutputStream.Write(buffer, 0, length); // // Flush the data to the HTML output. // Response.Flush(); // buffer = new Byte[300000]; // dataToRead = dataToRead - length; // } // else // { // //prevent infinite loop if user disconnects // dataToRead = -1; // } //} //if (iStream != null) //{ // //Close the file. // iStream.Close(); // iStream.Dispose(); //} //删除文件 if (!IsThum) { File.Delete(NewfilePath); } } else { System.Web.HttpContext.Current.Response.Write("<script>alert('该文件不存在!');</script>"); } //context.Response.ContentType = "text/plain"; //context.Response.Write("Hello World"); } catch (Exception ex) { // Trap the error, if any. Response.Write("下载出现异常Error : " + ex.Message); Response.Clear(); Response.End(); } finally { Response.End(); } }
protected void Page_Load(object sender, EventArgs e) { //UploadService bb = new UploadService(); //bb.CreateCompanyDirectory("703dfb3c-d3dc-4b1d-9bf0-3507ba01b716", "集团本部", "SMT"); SMT.Foundation.Log.Tracer.Debug("开始上传文件时间:" + System.DateTime.Now.ToString()); try { string NewPath = ""; HttpPostedFile fileData = Request.Files["Filedata"]; SMT.Foundation.Log.Tracer.Debug("开始上传文件的大小:" + fileData.ContentLength.ToString()); SMT.Foundation.Log.Tracer.Debug("开始上传文件:" + fileData.FileName); string filePath = ""; string companyCode = ""; //公司代码 string systemCode = ""; //系统代码 string modelCode = ""; //模块代码 string encryptName = ""; //加密字符串 string strFileName = ""; strFileName = fileData.FileName; UserFile model = null; string DownloadUrl = string.Concat(ConfigurationManager.AppSettings["DownLoadUrl"]); //获取用户身份,由用户名,密码组成 string StrAuthUser = string.Concat(ConfigurationManager.AppSettings["FileUploadUser"]); //if (Request["path"] != null) //{ // filePath = Request["path"].ToString(); // SMT.Foundation.Log.Tracer.Debug("上传文件完成,路径:" + filePath); //} if (Request["companyCode"] != null)//公司代码 { companyCode = Request["companyCode"].ToString(); model = FileConfig.GetCompanyItem(companyCode); SMT.Foundation.Log.Tracer.Debug("aspx页面上传文件companyCode:" + companyCode); } if (Request["systemCode"] != null)//系统代码 { systemCode = Request["systemCode"].ToString(); SMT.Foundation.Log.Tracer.Debug("aspx页面上传文件systemcode:" + systemCode); } if (Request["modelCode"] != null)//模块代码 { modelCode = Request["modelCode"].ToString(); SMT.Foundation.Log.Tracer.Debug("aspx页面上传文件modlecode:" + modelCode); } if (Request["encryptName"] != null)//加密文件名 { encryptName = Request["encryptName"].ToString(); SMT.Foundation.Log.Tracer.Debug("aspx页面上传文件encryptName:" + encryptName); } if (fileData != null) { //string path = ctx.Server.MapPath(ctx.Request["file"].ToString()); string strPath = string.Format(model.SavePath, companyCode, systemCode, modelCode); if (!System.IO.Directory.Exists(strPath)) { if (strPath.IndexOf("\\\\") == 0) { string FirstName = ""; string UserName = ""; string StrPwd = ""; string ComputerName = ""; if (StrAuthUser.IndexOf(",") > 0) { FirstName = StrAuthUser.Split(',')[0]; ComputerName = FirstName.Split('/')[0]; UserName = FirstName.Split('/')[1]; StrPwd = StrAuthUser.Split(',')[1]; } LogonImpersonate imper = new LogonImpersonate(UserName, StrPwd); string path = @"Z:\" + companyCode + @"\" + systemCode + @"\" + modelCode; string OldPath = model.SavePath.Split('{')[0].TrimEnd('\\'); if (CreateDirectory(path, UserName, StrPwd, OldPath)) { SMT.Foundation.Log.Tracer.Debug("aspx页面创建了驱动器映射"); } else { SMT.Foundation.Log.Tracer.Debug("aspx页面有创建映射问题"); } } else { System.IO.Directory.CreateDirectory(strPath); } } NewPath = Path.Combine(strPath, encryptName); //还未上传完成的路径 string OldFilePath = Path.Combine(strPath, strFileName); //原来上传的文件 string PassWordKey = ""; //加密字符串 if (encryptName.Length > 8) { PassWordKey = encryptName.Substring(0, 8); } else { PassWordKey = "12345678"; } int fileLength = fileData.ContentLength; byte[] data = new Byte[fileLength]; Stream fileStream = fileData.InputStream; fileStream.Read(data, 0, fileLength); SMT.Foundation.Log.Tracer.Debug("aspx页面上传文件开始,路径NewPath:" + NewPath); using (FileStream fs = File.Create(NewPath)) { fs.Write(data, 0, data.Length); fs.Close(); fs.Dispose(); } //创建上传过来的文件 SMT.Foundation.Log.Tracer.Debug("aspx页面上传文件开始,路径OldFilePath:" + OldFilePath); using (FileStream fsOld = File.Create(OldFilePath)) { fsOld.Write(data, 0, data.Length); fsOld.Close(); fsOld.Dispose(); } string strTempName = Path.Combine(strPath, encryptName);//已经上传完成的路径 SMT.Foundation.Log.Tracer.Debug("aspx页面上传文件开始,路径strTempName:" + strTempName); File.Move(NewPath, strTempName); NewPath = strTempName;//最近返回已完成的路径 string imageType = ".JPEG,.JPG,.GIF,.BMP"; //判断上传的模块的类型,如果是新闻则生成缩略图 #region 生成缩略图 string FileType = ""; if (imageType.IndexOf(FileType) > 0 || imageType.ToLower().IndexOf(FileType) > 0) { string thumbPath = string.Format(model.SavePath, companyCode, systemCode, modelCode) + "\\thumb\\"; SMT.Foundation.Log.Tracer.Debug("aspx页面上传图片文件,路径thumbPath:" + thumbPath); if (!System.IO.Directory.Exists(thumbPath)) { SMT.Foundation.Log.Tracer.Debug("aspx页面上传图片文件,不存在路径thumbPath:" + thumbPath); if (strPath.IndexOf("\\\\") == 0) { string FirstName = ""; string UserName = ""; string StrPwd = ""; string ComputerName = ""; if (StrAuthUser.IndexOf(",") > 0) { FirstName = StrAuthUser.Split(',')[0]; ComputerName = FirstName.Split('/')[0]; UserName = FirstName.Split('/')[1]; StrPwd = StrAuthUser.Split(',')[1]; } LogonImpersonate imper = new LogonImpersonate(UserName, StrPwd); string path = @"Z:\" + companyCode + @"\" + systemCode + @"\" + modelCode; string OldPath = model.SavePath.Split('{')[0].TrimEnd('\\'); if (CreateDirectory(path, UserName, StrPwd, OldPath)) { SMT.Foundation.Log.Tracer.Debug("创建了驱动器映射"); } else { SMT.Foundation.Log.Tracer.Debug("aspx页面图片上传有问题"); } } else { SMT.Foundation.Log.Tracer.Debug("aspx页面上传图片文件,开始创建路径thumbPath:" + thumbPath); System.IO.Directory.CreateDirectory(thumbPath); } } string thumbFile = thumbPath + encryptName; string strType = "JPG"; strType = FileType; MakeImageThumb.MakeThumbnail(OldFilePath, thumbFile, 250, 200, "DB", strType); //保存到数据库的路径 string strSaveThumb = string.Format("\\{0}\\{1}\\{2}", companyCode, systemCode, modelCode + "\\thumb\\" + encryptName); //entity.THUMBNAILURL = string.Format("\\{0}\\{1}\\{2}", model.CompanyCode, model.SystemCode, model.ModelCode + "\\" + strMd5Name); //entity.THUMBNAILURL = strSaveThumb; } #endregion CryptoHelp.EncryptFileForMVC(OldFilePath, NewPath, PassWordKey); //fileStream.Close(); //fileStream.Dispose(); SMT.Foundation.Log.Tracer.Debug("aspx页面上传文件完成,路径:" + NewPath + " tempName:" + strTempName); } } catch (Exception ex) { SMT.Foundation.Log.Tracer.Debug("上传文件upload.aspx页面出现错误:" + ex.ToString()); } }