关于文件上传下载? 哪位朋友有源码吗?谢谢啦,需要网页版的 解决方案 » 免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货 是WEB还是winformwebclient,ftpwebrequestweb fileupload,还有很多组件 FileInfo Fi = new FileInfo(filePath);if (Fi.Exists){ FileStream fs = new FileStream(filePath, FileMode.Open); byte[] bytes = new byte[(int)fs.Length]; fs.Read(bytes, 0, bytes.Length); fs.Close(); Response.ContentType = "application/octet-stream"; Response.AddHeader("Content-Disposition", "attachment; filename=1.excel"); Response.BinaryWrite(bytes); Response.Flush(); Response.End();}string path = Server.MapPath("~/") + "";Response.AppendHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(obj.Name, System.Text.Encoding.GetEncoding("utf-8")));Response.ContentType = "application/octet-stream";Response.WriteFile("" + path + "");Response.End();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); } public void UpLoadTheFile() { try { HttpPostedFile hpf = UpLoadFile.PostedFile; string path = Server.MapPath("~/"); //判断是不是当月的第一天 string firstDay = DateTime.Now.Day.ToString(); string intMonth = DateTime.Now.Month.ToString(); string intYear = DateTime.Now.Year.ToString(); if (firstDay == "1") //如果为当月第一天,创建文件夹 { System.IO.Directory.CreateDirectory(path + "ExcelDataReportUpFile/" + intYear + intMonth + firstDay); } else//否则,检测是否存在当月的文件夹,不存在则创建当月的,防止第一次上传文件时,没有文件夹报错. { if (!System.IO.Directory.Exists(path + "ExcelDataReportUpFile/" + intYear + intMonth + "1")) System.IO.Directory.CreateDirectory(path + "ExcelDataReportUpFile/" + intYear + intMonth + "1"); } string filename = hpf.FileName; //获得上传文件全路径 int place = filename.LastIndexOf(".") + 1; //获得文件扩展名的位置 string extname = filename.Substring(place); //获得上传文件的扩展名 string fileguid = System.Guid.NewGuid().ToString();//生成唯一标识 //生成文件名$后为文件夹名,以方便下载查找 string fullname = fileguid + "$" +intYear + intMonth + "1"+ "." + extname;//重新生成文件名 $为识别符号 string nowPath = intYear + intMonth + "1"; string imgpath = path + "ExcelDataReportUpFile/" + nowPath + "/" + fullname;//上传文件的存放路径 hpf.SaveAs(imgpath); //文件上传 //获取上传文件的信息,以存入数据库 addFile.CREA_DATE = DateTime.Now; addFile.FILE_EXT = extname; //附件说明为上传真实文件名 addFile.FILE_MEMO = filename.Substring(filename.LastIndexOf("\\") + 1); //NAME为唯一文件名 addFile.FILE_NAME = fullname; } catch(Exception err) { ErrHandle(err); } } 上传 if (!this.Page.IsPostBack) { string guid = Request.QueryString["GuID"]; try { if (Request.Files.Count > 1) { int gid = Request.Files.Count - 1; if (Request.Files[0].ContentLength < 1843200000) { string Dir = System.Configuration.ConfigurationManager.AppSettings["TemporyUpload"]; string path = Path.Combine(Dir, guid); string fileName = System.IO.Path.GetFileName(Request.Files[gid - 1].FileName); //if (System.IO.Path.GetFileName(Request.Files[1].FileName) != "") //{ // fileName = System.IO.Path.GetFileName(Request.Files[1].FileName); //} if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } Request.Files[0].SaveAs(Path.Combine(path, fileName)); //Byte a = Request.TotalBytes(); if (File.Exists(Path.Combine(path, fileName))) { // int gid = Request.Files.Count - 1; string js = @"<Script language='JavaScript'>parent.window.showSuccessText(" + gid + "); parent.window.deletePrgs(" + gid + "); </Script>"; // this.Page.ClientScript.RegisterStartupScript(this.GetType(), "uploadstate", "window.top.window.stopUpload(1);", true);//如果和页面建立长连接的话使用,可以实现进度条 this.Page.Response.Write(js); this.Page.Response.Flush(); fileName = ""; } else { } } } } catch (Exception ee) { string a = ee.Message; }下载 System.IO.FileInfo aFile = new System.IO.FileInfo(filePath); if (aFile.Exists) { context.Response.Clear(); context.Response.ClearHeaders(); context.Response.BufferOutput = false; context.Response.ContentType = "application/octet-stream"; context.Response.AppendHeader("Content-disposition", "attachment;filename=" + HttpUtility.UrlEncode(aFile.Name, System.Text.Encoding.UTF8)); context.Response.AddHeader("Content-Length", aFile.Length.ToString()); context.Response.WriteFile(filePath); context.Response.Flush(); context.Response.End(); } google搜索,首先要确定你的winform还是asp.net? csdn上的下载资源可是很多的哟, #region post方式发送数据 /// <summary> /// post方式发送数据 /// </summary> /// <param name="url">url</param> //string url = "http://localhost:1198/AutoTicket_Notify.aspx"; /// <param name="postdata">发送的数据</param> // string postdata = "ticketnoinfo=info&username=name&pwd=word"; /// <returns>返回的结果</returns> //下载用get,上传用post public string SendDataByPost(string url, string postdata) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = postdata.Length; Stream requestStream = request.GetRequestStream(); StreamWriter streamWriter = new StreamWriter(requestStream, Encoding.GetEncoding("gb2312")); streamWriter.Write(postdata); streamWriter.Close(); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream responseStream = response.GetResponseStream(); StreamReader streamReader = new StreamReader(responseStream, Encoding.GetEncoding("gb2312")); string result = streamReader.ReadToEnd(); streamReader.Close(); responseStream.Close(); return result; } #endregion #region Get方式获取数据 /// <summary> /// Get方式获取数据 /// </summary> /// <param name="url">url</param> /// <param name="postdata">发送的数据</param> /// <returns>获取到的结果数据</returns> public string GetDataByGet(string url, string postdata) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url + (postdata == "" ? "" : "?") + postdata); request.Method = "GET"; request.ContentType = "text/xml;charset=gb2312"; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream responseStream = response.GetResponseStream(); StreamReader streamReader = new StreamReader(responseStream, Encoding.GetEncoding("gb2312")); string result = streamReader.ReadToEnd(); streamReader.Close(); responseStream.Close(); return result; } #endregion #region 同步通过GET方式发送数据 /// <summary> /// 通过GET方式发送数据 /// </summary> /// <param name="Url">url</param> /// <param name="postDataStr">GET数据</param> /// <param name="cookie">GET容器</param> /// <returns></returns> public static string SendDataByGET(string Url, string postDataStr) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + (postDataStr == "" ? "" : "?") + postDataStr); request.Method = "GET"; request.ContentType = "text/html;charset=UTF-8"; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream myResponseStream = response.GetResponseStream(); StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8")); string retString = myStreamReader.ReadToEnd(); myStreamReader.Close(); myResponseStream.Close(); return retString; } #endregion ASP.NET将文件放在项目中protected void lbtnDownload_Click(object sender, EventArgs e) { string strPath = Server.MapPath("你所存放文件路径"); if (strPath != "") { FileInfo FInfo = new FileInfo(strPath); //使用获得的路径实例化FileInfo对象 if (FInfo.Exists) //判断附件是否存在 { Response.Clear(); //清空缓冲区 Response.ClearHeaders(); //清空缓冲区头 Response.Buffer = false; //设置Response对象不可以缓冲输出 Response.ContentType = "application/octet-stream"; //设置输出流的HTTP MIME类型 Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(FInfo.FullName, System.Text.Encoding.UTF8)); //将HTTP头添加到输出流 Response.AppendHeader("Content-Length", FInfo.Length.ToString()); //将要下载的附件大小添加到输出流 Response.WriteFile(FInfo.FullName); //将指定的附件写入输出流 Response.Flush(); //向客户发送当前所有缓冲的输出 Response.End(); } } } 如果想实现真进度条的话,建议使用flash或者activeX,否则就算用的是StreamReader读取到流,在分块存到目录的操作都是做无用功,无非是先将数据读到了服务器的内存中,再从内存中写文件(测已试过)。 网上应该很多,不过不知道lz说的是Web还是WinForm~~ VS上的控件就能实现 你的问题啊 多看看MSDN吧 项目源码 我有几个你现看看这个不行 我再发给你http://www.51aspx.com/CV/uploaddown/ if (System.IO.File.Exists(filePath)) { FileInfo file = new FileInfo(filePath); Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8"); //解决中文乱码 Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(file.Name)); //解决中文文件名乱码 Response.AddHeader("Content-length", file.Length.ToString()); Response.ContentType = "appliction/octet-stream"; Response.WriteFile(file.FullName); Response.End(); RegisterClientScriptBlock("", "<script>alert('下载成功')</script>"); } else { RegisterClientScriptBlock("", "<script>alert('文件不存在')</script>"); } 网页版的肯定是Asp.NET的 啊!! using System;using System.Collections.Generic;using System.Data;using System.Windows.Forms;using System.Data.SqlClient;using System.IO;namespace SaveImageToSqlServer{ public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void buttonSaveImageToDataServer_Click(object sender, EventArgs e) { if (DialogResult.OK == this.folderBrowserDialog1.ShowDialog()) { string dirName = this.folderBrowserDialog1.SelectedPath; DirectoryInfo dir = new DirectoryInfo(dirName); FileInfo[] fileInfos = dir.GetFiles("*.jpg"); List<string> fileList = new List<string>(100); foreach (FileInfo fileInfo in fileInfos) { fileList.Add(fileInfo.FullName); System.Windows.Forms.Application.DoEvents(); } #region Save data to Data Server string strConn = @"Server=(local);" + @"Initial Catalog=test;" + @"User Id =yujian;" + @"Password=;" + @"Integrated Security = true"; try { using (SqlConnection sqlConnection = new SqlConnection(strConn)) { sqlConnection.Open(); foreach (string file in fileList) { FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read); byte[] byteImage = new byte[fileStream.Length]; fileStream.Read(byteImage, 0, (int)fileStream.Length); string commandText = "Insert into ImageTable(ImagePath, Image)Values(@ImagePath, @Image)"; SqlCommand sqlCommand = new SqlCommand(commandText, sqlConnection); sqlCommand.Parameters.Add("@ImagePath", SqlDbType.Text); sqlCommand.Parameters.Add("@Image", SqlDbType.Binary); sqlCommand.Parameters["@ImagePath"].Value = file; sqlCommand.Parameters["@Image"].Value = byteImage; sqlCommand.ExecuteNonQuery(); System.Windows.Forms.Application.DoEvents(); } } } catch (SqlException ex) { MessageBox.Show(ex.ToString()); } #endregion MessageBox.Show("Save data OK."); } } private void buttonShowImage_Click(object sender, EventArgs e) { string strConn = @"Server=(local);" + @"Initial Catalog=test;" + @"User id=yujian;" + @"Password=;" + @"Integrated Security=true;"; try { using (SqlConnection sqlConnection = new SqlConnection(strConn)) { sqlConnection.Open(); string commandText = "Select ImagePath, Image from ImageTable"; SqlDataAdapter adapter = new SqlDataAdapter(commandText, sqlConnection); DataTable dt = new DataTable(); adapter.Fill(dt); this.dataGridView1.DataSource = dt; sqlConnection.Close(); } } catch (SqlException ex) { MessageBox.Show(ex.ToString()); } } }} //文件上传 private void Form2_Load(object sender, EventArgs e) { if (DialogResult.OK == this.folderBrowserDialog1.ShowDialog()) { string dirName = this.folderBrowserDialog1.SelectedPath; DirectoryInfo dir = new DirectoryInfo(dirName); FileInfo[] fileInfos = dir.GetFiles("*.jpg"); List<string> fileList = new List<string>(100); foreach (FileInfo fileInfo in fileInfos) { fileList.Add(fileInfo.FullName); System.Windows.Forms.Application.DoEvents(); } string strConn = @"Server=(local);" + @"Initial Catalog=test;" + @"User Id =yujian;" + @"Password=;" + @"Integrated Security = true"; try { using (SqlConnection sqlConnection = new SqlConnection(strConn)) { sqlConnection.Open(); foreach (string file in fileList) { FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read); byte[] byteImage = new byte[fileStream.Length]; fileStream.Read(byteImage, 0, (int)fileStream.Length); string commandText = "Insert into ImageTable(ImagePath, Image)Values(@ImagePath, @Image)"; SqlCommand sqlCommand = new SqlCommand(commandText, sqlConnection); sqlCommand.Parameters.Add("@ImagePath", SqlDbType.Text); sqlCommand.Parameters.Add("@Image", SqlDbType.Binary); sqlCommand.Parameters["@ImagePath"].Value = file; sqlCommand.Parameters["@Image"].Value = byteImage; sqlCommand.ExecuteNonQuery(); System.Windows.Forms.Application.DoEvents(); } } } catch (SqlException ex) { MessageBox.Show(ex.ToString()); } } } // 文件下载 private void button1_Click(object sender, EventArgs e) { string strConn = @"Server=(local);" + @"Initial Catalog=test;" + @"User id=yujian;" + @"Password=;" + @"Integrated Security=true;"; try { using (SqlConnection sqlConnection = new SqlConnection(strConn)) { sqlConnection.Open(); string commandText = "Select ImagePath, Image from ImageTable"; SqlDataAdapter adapter = new SqlDataAdapter(commandText, sqlConnection); DataTable dt = new DataTable(); adapter.Fill(dt); this.dataGridView1.DataSource = dt; sqlConnection.Close(); } } catch (SqlException ex) { MessageBox.Show(ex.ToString()); } } string nam = myFile.PostedFile.FileName; //取得文件名(包括路径)里最后一个"."的索引 int i = nam.LastIndexOf("."); //取得文件扩展名 string newext = nam.Substring(i); //这里自动根据日期和文件大小不同为文件命名,确保文件名不重复。 //DateTime now = DateTime.Now; //string newname = now.DayOfYear.ToString() + myFile.PostedFile.ContentLength.ToString(); //保存文件到你所要的目录,这里是IIS根目录下的upfiles目录.你可以改变. //注意: 我这里用Server.MapPath()取当前文件的绝对目录.在asp.net里"\"必须用"\\"代替 myFile.PostedFile.SaveAs(Server.MapPath("~\\UploadFiles\\file\\" + TextBox1.Text.Trim() + newext));下载直接搞个链接就行了web.config中加入 <system.web> <httpRuntime executionTimeout="90" maxRequestLength="100000" useFullyQualifiedRedirectUrl="false" /> </system.web> 红色表示上传的文件大小 下载 string path = Server.MapPath("~/Upload/" + file.FilePath); if (System.IO.File.Exists(path)) { System.IO.FileStream fs = null; try { fs = new System.IO.FileStream(path, System.IO.FileMode.Open); byte[] buffer = new byte[(int)fs.Length]; fs.Read(buffer, 0, buffer.Length); Response.ContentType = "application/octet-stream"; //通知浏览器下载文件而不是打开 Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode (file.FilePath, System.Text.Encoding.UTF8)); Response.BinaryWrite(buffer); Response.Flush(); Response.End(); } finally { if (fs != null) { fs.Close(); } } }上传 if (File.Exists(Server.MapPath("~/Upload/" + FileUpload1.FileName))) { MessageBox.Show(this, "该文件已经存在"); } else { try { DayLogInfo log = new DayLogInfo(); if (FileUpload1.HasFile) { log.FilePath = FileUpload1.FileName; HttpPostedFile pf = FileUpload1.PostedFile; pf.SaveAs(Server.MapPath("~/Upload/" + FileUpload1.FileName)); } }}} http://blog.csdn.net/a13623127108/archive/2010/07/21/5753290.aspx winform的 看看吧或许有用 使用vs2010旗舰版,dataGridView1绑定数据的问题?付源码 如何读取EXCEL文件并SQL里面的标准匹配啊 数据库访问是否可以更简单,ORM是否可以再简化?这次是ORM部分。 新装的vs2005新建项目,没有解决方案,添加不了项目 C# 如何获取控制台打印内容 .net 直接输出打印条码 求助!調整.net安全性. 数据邦定后显示不出来????晕!!!!请高手进来LOOK LOOK GridView删除最后一行的问题 怎样实现C#里面两个不同项目之间窗体的引用呢 一个关于在Gridview里显示数据的问题 求用C#语言编写的记录键盘输入的源代码
webclient,ftpwebrequest
web fileupload,还有很多组件
if (Fi.Exists)
{
FileStream fs = new FileStream(filePath, FileMode.Open);
byte[] bytes = new byte[(int)fs.Length];
fs.Read(bytes, 0, bytes.Length);
fs.Close();
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment; filename=1.excel");
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}
string path = Server.MapPath("~/") + "";
Response.AppendHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(obj.Name, System.Text.Encoding.GetEncoding("utf-8")));
Response.ContentType = "application/octet-stream";
Response.WriteFile("" + path + "");
Response.End();
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);
}
{
try
{
HttpPostedFile hpf = UpLoadFile.PostedFile;
string path = Server.MapPath("~/");
//判断是不是当月的第一天
string firstDay = DateTime.Now.Day.ToString();
string intMonth = DateTime.Now.Month.ToString();
string intYear = DateTime.Now.Year.ToString();
if (firstDay == "1") //如果为当月第一天,创建文件夹
{
System.IO.Directory.CreateDirectory(path + "ExcelDataReportUpFile/" + intYear + intMonth + firstDay);
}
else//否则,检测是否存在当月的文件夹,不存在则创建当月的,防止第一次上传文件时,没有文件夹报错.
{
if (!System.IO.Directory.Exists(path + "ExcelDataReportUpFile/" + intYear + intMonth + "1"))
System.IO.Directory.CreateDirectory(path + "ExcelDataReportUpFile/" + intYear + intMonth + "1");
}
string filename = hpf.FileName; //获得上传文件全路径
int place = filename.LastIndexOf(".") + 1; //获得文件扩展名的位置
string extname = filename.Substring(place); //获得上传文件的扩展名 string fileguid = System.Guid.NewGuid().ToString();//生成唯一标识
//生成文件名$后为文件夹名,以方便下载查找
string fullname = fileguid + "$" +intYear + intMonth + "1"+ "." + extname;//重新生成文件名 $为识别符号
string nowPath = intYear + intMonth + "1"; string imgpath = path + "ExcelDataReportUpFile/" + nowPath + "/" + fullname;//上传文件的存放路径 hpf.SaveAs(imgpath); //文件上传
//获取上传文件的信息,以存入数据库
addFile.CREA_DATE = DateTime.Now;
addFile.FILE_EXT = extname;
//附件说明为上传真实文件名
addFile.FILE_MEMO = filename.Substring(filename.LastIndexOf("\\") + 1);
//NAME为唯一文件名
addFile.FILE_NAME = fullname;
}
catch(Exception err)
{
ErrHandle(err);
}
}
{
string guid = Request.QueryString["GuID"];
try
{
if (Request.Files.Count > 1)
{
int gid = Request.Files.Count - 1;
if (Request.Files[0].ContentLength < 1843200000)
{
string Dir = System.Configuration.ConfigurationManager.AppSettings["TemporyUpload"];
string path = Path.Combine(Dir, guid);
string fileName = System.IO.Path.GetFileName(Request.Files[gid - 1].FileName);
//if (System.IO.Path.GetFileName(Request.Files[1].FileName) != "")
//{
// fileName = System.IO.Path.GetFileName(Request.Files[1].FileName);
//}
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
Request.Files[0].SaveAs(Path.Combine(path, fileName));
//Byte a = Request.TotalBytes(); if (File.Exists(Path.Combine(path, fileName)))
{
// int gid = Request.Files.Count - 1;
string js = @"<Script language='JavaScript'>parent.window.showSuccessText(" + gid + "); parent.window.deletePrgs(" + gid + "); </Script>";
// this.Page.ClientScript.RegisterStartupScript(this.GetType(), "uploadstate", "window.top.window.stopUpload(1);", true);//如果和页面建立长连接的话使用,可以实现进度条
this.Page.Response.Write(js);
this.Page.Response.Flush(); fileName = "";
}
else
{ }
}
}
}
catch (Exception ee)
{
string a = ee.Message;
}
下载 System.IO.FileInfo aFile = new System.IO.FileInfo(filePath);
if (aFile.Exists)
{
context.Response.Clear();
context.Response.ClearHeaders();
context.Response.BufferOutput = false;
context.Response.ContentType = "application/octet-stream";
context.Response.AppendHeader("Content-disposition", "attachment;filename=" + HttpUtility.UrlEncode(aFile.Name, System.Text.Encoding.UTF8));
context.Response.AddHeader("Content-Length", aFile.Length.ToString());
context.Response.WriteFile(filePath);
context.Response.Flush();
context.Response.End();
}
/// <summary>
/// post方式发送数据
/// </summary>
/// <param name="url">url</param> //string url = "http://localhost:1198/AutoTicket_Notify.aspx";
/// <param name="postdata">发送的数据</param> // string postdata = "ticketnoinfo=info&username=name&pwd=word";
/// <returns>返回的结果</returns> //下载用get,上传用post
public string SendDataByPost(string url, string postdata)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postdata.Length;
Stream requestStream = request.GetRequestStream();
StreamWriter streamWriter = new StreamWriter(requestStream, Encoding.GetEncoding("gb2312"));
streamWriter.Write(postdata);
streamWriter.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader streamReader = new StreamReader(responseStream, Encoding.GetEncoding("gb2312"));
string result = streamReader.ReadToEnd();
streamReader.Close();
responseStream.Close();
return result;
}
#endregion
#region Get方式获取数据
/// <summary>
/// Get方式获取数据
/// </summary>
/// <param name="url">url</param>
/// <param name="postdata">发送的数据</param>
/// <returns>获取到的结果数据</returns>
public string GetDataByGet(string url, string postdata)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url + (postdata == "" ? "" : "?") + postdata);
request.Method = "GET";
request.ContentType = "text/xml;charset=gb2312";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader streamReader = new StreamReader(responseStream, Encoding.GetEncoding("gb2312"));
string result = streamReader.ReadToEnd();
streamReader.Close();
responseStream.Close();
return result;
}
#endregion
#region 同步通过GET方式发送数据
/// <summary>
/// 通过GET方式发送数据
/// </summary>
/// <param name="Url">url</param>
/// <param name="postDataStr">GET数据</param>
/// <param name="cookie">GET容器</param>
/// <returns></returns>
public static string SendDataByGET(string Url, string postDataStr)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + (postDataStr == "" ? "" : "?") + postDataStr);
request.Method = "GET";
request.ContentType = "text/html;charset=UTF-8"; HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream myResponseStream = response.GetResponseStream();
StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
string retString = myStreamReader.ReadToEnd();
myStreamReader.Close();
myResponseStream.Close(); return retString;
}
#endregion
protected void lbtnDownload_Click(object sender, EventArgs e)
{
string strPath = Server.MapPath("你所存放文件路径");
if (strPath != "")
{
FileInfo FInfo = new FileInfo(strPath); //使用获得的路径实例化FileInfo对象
if (FInfo.Exists) //判断附件是否存在
{
Response.Clear(); //清空缓冲区
Response.ClearHeaders(); //清空缓冲区头
Response.Buffer = false; //设置Response对象不可以缓冲输出
Response.ContentType = "application/octet-stream"; //设置输出流的HTTP MIME类型
Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(FInfo.FullName, System.Text.Encoding.UTF8)); //将HTTP头添加到输出流
Response.AppendHeader("Content-Length", FInfo.Length.ToString()); //将要下载的附件大小添加到输出流
Response.WriteFile(FInfo.FullName); //将指定的附件写入输出流
Response.Flush(); //向客户发送当前所有缓冲的输出
Response.End(); }
} }
你现看看这个不行 我再发给你
http://www.51aspx.com/CV/uploaddown/
{
FileInfo file = new FileInfo(filePath);
Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8"); //解决中文乱码
Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(file.Name)); //解决中文文件名乱码
Response.AddHeader("Content-length", file.Length.ToString());
Response.ContentType = "appliction/octet-stream";
Response.WriteFile(file.FullName);
Response.End();
RegisterClientScriptBlock("", "<script>alert('下载成功')</script>");
}
else
{
RegisterClientScriptBlock("", "<script>alert('文件不存在')</script>");
}
private void Form2_Load(object sender, EventArgs e)
{
if (DialogResult.OK == this.folderBrowserDialog1.ShowDialog())
{
string dirName = this.folderBrowserDialog1.SelectedPath;
DirectoryInfo dir = new DirectoryInfo(dirName);
FileInfo[] fileInfos = dir.GetFiles("*.jpg");
List<string> fileList = new List<string>(100);
foreach (FileInfo fileInfo in fileInfos)
{
fileList.Add(fileInfo.FullName);
System.Windows.Forms.Application.DoEvents();
}
string strConn = @"Server=(local);" + @"Initial Catalog=test;" + @"User Id =yujian;" + @"Password=;" + @"Integrated Security = true";
try
{
using (SqlConnection sqlConnection = new SqlConnection(strConn))
{
sqlConnection.Open(); foreach (string file in fileList)
{
FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read);
byte[] byteImage = new byte[fileStream.Length];
fileStream.Read(byteImage, 0, (int)fileStream.Length);
string commandText = "Insert into ImageTable(ImagePath, Image)Values(@ImagePath, @Image)";
SqlCommand sqlCommand = new SqlCommand(commandText, sqlConnection);
sqlCommand.Parameters.Add("@ImagePath", SqlDbType.Text);
sqlCommand.Parameters.Add("@Image", SqlDbType.Binary);
sqlCommand.Parameters["@ImagePath"].Value = file;
sqlCommand.Parameters["@Image"].Value = byteImage;
sqlCommand.ExecuteNonQuery(); System.Windows.Forms.Application.DoEvents();
}
}
}
catch (SqlException ex)
{
MessageBox.Show(ex.ToString());
}
}
}
// 文件下载
private void button1_Click(object sender, EventArgs e)
{
string strConn = @"Server=(local);" + @"Initial Catalog=test;" + @"User id=yujian;" + @"Password=;" + @"Integrated Security=true;";
try
{
using (SqlConnection sqlConnection = new SqlConnection(strConn))
{
sqlConnection.Open(); string commandText = "Select ImagePath, Image from ImageTable";
SqlDataAdapter adapter = new SqlDataAdapter(commandText, sqlConnection);
DataTable dt = new DataTable();
adapter.Fill(dt);
this.dataGridView1.DataSource = dt; sqlConnection.Close();
}
}
catch (SqlException ex)
{
MessageBox.Show(ex.ToString());
}
}
//取得文件名(包括路径)里最后一个"."的索引
int i = nam.LastIndexOf("."); //取得文件扩展名
string newext = nam.Substring(i);
//这里自动根据日期和文件大小不同为文件命名,确保文件名不重复。
//DateTime now = DateTime.Now;
//string newname = now.DayOfYear.ToString() + myFile.PostedFile.ContentLength.ToString(); //保存文件到你所要的目录,这里是IIS根目录下的upfiles目录.你可以改变.
//注意: 我这里用Server.MapPath()取当前文件的绝对目录.在asp.net里"\"必须用"\\"代替 myFile.PostedFile.SaveAs(Server.MapPath("~\\UploadFiles\\file\\" + TextBox1.Text.Trim() + newext));
下载
直接搞个链接就行了web.config中加入
<system.web>
<httpRuntime executionTimeout="90" maxRequestLength="100000" useFullyQualifiedRedirectUrl="false" />
</system.web>
红色表示上传的文件大小
string path = Server.MapPath("~/Upload/" + file.FilePath);
if (System.IO.File.Exists(path))
{
System.IO.FileStream fs = null;
try
{ fs = new System.IO.FileStream(path, System.IO.FileMode.Open);
byte[] buffer = new byte[(int)fs.Length];
fs.Read(buffer, 0, buffer.Length);
Response.ContentType = "application/octet-stream";
//通知浏览器下载文件而不是打开
Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode
(file.FilePath, System.Text.Encoding.UTF8));
Response.BinaryWrite(buffer);
Response.Flush();
Response.End();
}
finally
{
if (fs != null)
{
fs.Close();
}
}
}上传 if (File.Exists(Server.MapPath("~/Upload/" + FileUpload1.FileName)))
{
MessageBox.Show(this, "该文件已经存在");
}
else
{
try
{
DayLogInfo log = new DayLogInfo();
if (FileUpload1.HasFile)
{
log.FilePath = FileUpload1.FileName;
HttpPostedFile pf = FileUpload1.PostedFile;
pf.SaveAs(Server.MapPath("~/Upload/" + FileUpload1.FileName));
}
}
}
}
winform的 看看吧或许有用