asp.net 求客户端上传文件至服务器及客户端从服务器下载。

永动bug制造机 2011-10-13 11:18:19
rt

搜了几段代码都有问题。客户端或者服务器端路劲分别是如何获取 求解。
...全文
127 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
YnSky 2011-10-14
  • 打赏
  • 举报
回复
上传到服务器上.然后根据路径下载就可以了!
主要是路径要正确!
fox123871 2011-10-14
  • 打赏
  • 举报
回复
服务器端获取地址 就是一个server。mappath(‘文件’)生成一个绝对地址!
永动bug制造机 2011-10-14
  • 打赏
  • 举报
回复
[Quote=引用 5 楼 liuchaolin 的回复:]
FTP?
[/Quote]
not ftp
md5e 2011-10-14
  • 打赏
  • 举报
回复
FTP?
老牛10岁了 2011-10-14
  • 打赏
  • 举报
回复
。。。。这不是上传下载功能吗?应该不难啊。
SomethingJack 2011-10-13
  • 打赏
  • 举报
回复
下载

using System;
using System.Collections;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;

namespace Asiastar.NR.Ajax
{
/// <summary>
/// $codebehindclassname$ 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class Handler1 : IHttpHandler
{

public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
string id = context.Request["id"].ToString();//获取资源的编号
System.IO.Stream iStream = null;
byte[] buffer = new Byte[10000];
int length;
long dataToRead;
NRBLL.File bf = new Asiastar.NRBLL.File();
Guid guid = new Guid(id);
if( bf.FN_SerchPathByFileId(guid).Tables[0].Rows[0]["FilePath"] != null )//判断数据库路径是否存在
{
string filepath = bf.FN_SerchPathByFileId(guid).Tables[0].Rows[0]["FilePath"].ToString();//获取资源完整路径 D:\资源文件\600cc139-14cf-448e-9e50-daa972d35e01.jpg
string Oidfilename = bf.FN_SerchPathByFileId(guid).Tables[0].Rows[0]["FileNam"].ToString();//旧文件名称
//string filename = System.IO.Path.GetFileName(filepath);//获取文件名称+后缀名 600cc139-14cf-448e-9e50-daa972d35e01.JPG
//int index = filepath.IndexOf(".");
//string filetype = filepath.Substring(index).ToLower();//后缀名
//string newfilename = Oidfilename;
//string filepath1 = bf.FN_SerchPathByFileId(guid).Tables[0].Rows[0]["FilePath"].ToString().Substring(0,filepath.Length - 8);
try
{
string fileName = HttpUtility.UrlEncode(System.Text.Encoding.UTF8.GetBytes(Oidfilename));//解码(注意这里2层解码)
Oidfilename = Oidfilename.Replace("+","%20"); //将“+”替换成“空格”
iStream = new System.IO.FileStream(filepath,System.IO.FileMode.Open,System.IO.FileAccess.Read,System.IO.FileShare.Read);
dataToRead = iStream.Length;
context.Response.ContentType = "application/octet-stream";
context.Response.AddHeader("Content-Disposition","attachment; filename=" + HttpUtility.UrlEncode(Oidfilename,System.Text.Encoding.UTF8)); //下载的时候下载原来的文件名称
while( dataToRead > 0 )
{
if( context.Response.IsClientConnected )
{
length = iStream.Read(buffer,0,10000);
context.Response.OutputStream.Write(buffer,0,length);
context.Response.Flush();
buffer = new Byte[10000];
dataToRead = dataToRead - length;
}
else
{
dataToRead = -1;
}
}

}
catch( Exception ex )
{
NR.Error.Log.LogType(ex.ToString());
}
finally
{
if( iStream != null )
{
iStream.Close();
}
}
}
else
{
NR.Error.Log.LogType("找不到文件!");
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
}

SomethingJack 2011-10-13
  • 打赏
  • 举报
回复
上传.
页面放一个HTML的 inputfile

#region 上传文件到数据库和服务器
public void FN_UpFiles()
{

//遍历File表单元素
HttpFileCollection files = HttpContext.Current.Request.Files;
StringBuilder strMsg = new StringBuilder();
strMsg.Append("上传的文件分别是:<hr color='pink'/>");
try
{
for( int iFile = 0 ; iFile < files.Count ; iFile++ )
{
//检查文件扩展名字
HttpPostedFile postedFile = files[iFile];
string fileName = "";//定义文件名
string fileExtension = "";
fileName = Path.GetFileName(postedFile.FileName);//得到上传文件的完整名称 即文件名+后缀名
int index = fileName.IndexOf(".");
string FileType = fileName.Substring(index).ToLower();//截取文件后缀名
//FileTypeImg = "../FileTypeimg/" + hz + ".gif";
Guid fileGuid = Guid.NewGuid();//生成新的文件名称 以GUID命名防止文件名相同
string NewFileName = fileGuid.ToString();//新的文件名
NewFileName = NewFileName + FileType;//新的文件名+后缀名
if( postedFile.ContentLength > 2097151 * 1024 )//判断是否大于配置文件中的上传文件大小
{
Page.RegisterStartupScript("提示","<script language='javascript'>alert('对不起您的上传资源过大!');self.opener.location.reload();window.close();</script>");
return;
}
else
{
if( fileName != "" )//如果文件名不为空
{
try
{
//文件虚拟路径
string strpath = System.Web.HttpContext.Current.Server.MapPath("~/Upload/") + NewFileName;
try
{
NRModel.File model = new NRModel.File();
NRBLL.File bf = new NRBLL.File();
Guid guid1 = Guid.NewGuid();
Guid guid2 = new Guid(FolderId);
Guid guid3 = Guid.NewGuid();
Guid guid4 = Guid.NewGuid();
model.Fileid = guid1;
model.Folderid = guid2;
model.Filepath = strpath;
model.FileNam = fileName;
model.FileSize = postedFile.ContentLength;
model.Decription = TextArea1.InnerText.ToString();
model.CreateOn = DateTime.Now;
model.CreateBy = guid3;
model.ModefyBy = guid4;
if( bf.FN_AddNewRes(model) > 0 )
{
NR.Error.Log.LogType("上传资源" + fileName + "成功!" + "服务器路径:" + strpath);
//保存文件到指定目录(虚拟目录)
postedFile.SaveAs(System.Web.HttpContext.Current.Server.MapPath("~/Upload/") + NewFileName);
Page.RegisterStartupScript("提示","<script language='javascript'>alert('上传成功!');self.opener.location.reload();window.close();</script>");
}
}
catch( Exception ex )
{
NR.Error.Log.LogType(ex.ToString());
}

}
catch( Exception ex )
{
NR.Error.Log.LogType(ex.ToString());
}
}
else
{
Response.Write("上传文件不能为空!");
NR.Error.Log.LogType("文件不能为空!");
}
}

}
}
catch( System.Exception ex )
{
NR.Error.Log.LogType(ex.ToString());
}
}
#endregion

wengfuguil 2011-10-13
  • 打赏
  • 举报
回复
internal readonly string AllowExt = "txt|doc|docx|ppt|pptx|xls|xlsx|jpg|gif|bmp|psd|cdr|ai|pdf|eps|dwg|3ds|max|plt|rar|zip";

/// <summary>
/// 检测扩展名的有效性
/// </summary>
/// <param name="sExt">文件名扩展名</param>
/// <returns>如果扩展名有效,返回true,否则返回false.</returns>
bool CheckValidExt(string sExt)
{
bool flag = false;
string[] aExt = AllowExt.Split('|');
foreach (string filetype in aExt)
{
if (filetype.ToLower() == sExt.Replace(".", ""))
{
flag = true;
break;
}
}
return flag;
}
protected void butfile_Click(object sender, EventArgs e)
{
try
{
if (file1.HasFile)
{
//判断文件格式
string sExt = file1.FileName.Substring(file1.FileName.LastIndexOf(".")).ToLower();
if (!CheckValidExt(sExt))
{
ltMain.Text = "(原图片文件格式不正确!支持的格式有[ " + AllowExt + " ])";
return;
}
////判断文件大小
//int intFileLength = file1.PostedFile.ContentLength;

//if (intFileLength > 1000 * 1000)
//{
// this.ltMain.Text = "文件大于1M,不能上传!";
// return;
//}

Random ran = new Random();

string UpDir = "~/File/" + DateTime.Now.ToString("yyyyMM"); //上传目录
if (!Directory.Exists(Server.MapPath(UpDir)))
{
Directory.CreateDirectory(Server.MapPath(UpDir));
if (!Directory.Exists(Server.MapPath(UpDir)))
return; //如果创建失败则返回
}
//上传文件重命名:时间+三位随机数
string fileName = UpDir + "/" + DateTime.Now.ToString("yyyyMMddHHmmss")+file1.FileName;
Session["fileURL"] = fileName;
FileName = file1.FileName;
file1.PostedFile.SaveAs(HttpContext.Current.Server.MapPath(fileName));
fileUrl = fileName.Replace("~/", "");
ltMain.Text = fileName + "上传成功!";

}
else
ltMain.Text = "请选择文件!";
return;

}
catch
{
ltMain.Text = "发生错误,请重新上传文件!";
}
上传文件代码
永动bug制造机 2011-10-13
  • 打赏
  • 举报
回复
主要是客户端路径容易跟服务器端路径混淆 客户端路径如何获取。。。

62,046

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术交流专区
javascript云原生 企业社区
社区管理员
  • ASP.NET
  • .Net开发者社区
  • R小R
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

.NET 社区是一个围绕开源 .NET 的开放、热情、创新、包容的技术社区。社区致力于为广大 .NET 爱好者提供一个良好的知识共享、协同互助的 .NET 技术交流环境。我们尊重不同意见,支持健康理性的辩论和互动,反对歧视和攻击。

希望和大家一起共同营造一个活跃、友好的社区氛围。

试试用AI创作助手写篇文章吧