您的位置:首页 > 其它

(原创)文件安全下载

2009-12-09 15:14 204 查看
1、IIS设置

1)启动IIS.

2)创建一个新的名字为Security的虚拟目录.

  如图设置:

代码

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Net;
using System.IO;
namespace security
{
/// <SUMMARY>

/// </SUMMARY>
public class SecureFile
{
public SecureFile()
{

}
public bool UploadFile(HtmlInputFile inputfile)
{
try
{
string fileName = "";
string DirPath = "";

if(( inputfile.PostedFile != null ) &&
( inputfile.PostedFile.ContentLength > 0 ))
{
DirPath=HttpContext.Current.Server.MapPath(
System.Configuration.ConfigurationSettings.AppSettings[
"UploadPath"]);
fileName = System.IO.Path.GetFileName(
inputfile.PostedFile.FileName );
inputfile.PostedFile.SaveAs( DirPath + "\\\" + fileName );
}
return true;
}
catch
{
return false;
}
}

public bool DownloadFile(string strFile)
{
try
{
string strDownloadURL=
System.Configuration.ConfigurationSettings.AppSettings[
"DownloadURL"];
string strUser=
System.Configuration.ConfigurationSettings.AppSettings[
"BasicAuthenticationUser"];
string strPWD=
System.Configuration.ConfigurationSettings.AppSettings[
"BasicAuthenticationPWD"];
string strURL=strDownloadURL + "\\\" + strFile;

WebClient req=new WebClient();

CredentialCache mycache=new CredentialCache();
mycache.Add(new Uri(strURL),"Basic",
new NetworkCredential(strUser,strPWD));
req.Credentials=mycache;
HttpResponse response = HttpContext.Current.Response;
response.Clear();
response.ClearContent();
response.ClearHeaders();
response.Buffer= true;

response.AddHeader("Content-Disposition",
"attachment;filename=\"" + strFile + "\"");
byte[] data=req.DownloadData(strURL);
response.BinaryWrite(data);
response.End();
return true;
}
catch(Exception ex)
{
if(ex.Message=="The remote server " +
"returned an error: (404) Not Found.")
throw new Exception("File not found");
else if(ex.Message=="The remote server" +
" returned an error: (401) Unauthorized.")
throw new Exception("Unauthorized access");

return false;
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: