关于文件上传下载?

贫僧又回来了 2010-07-20 08:44:44
哪位朋友有源码吗?谢谢啦,需要网页版的
...全文
320 26 打赏 收藏 转发到动态 举报
写回复
用AI写文章
26 条回复
切换为时间正序
请发表友善的回复…
发表回复
xxccccxxxewe 2010-07-23
  • 打赏
  • 举报
回复
快点给分
a13623127108 2010-07-23
  • 打赏
  • 举报
回复
http://blog.csdn.net/a13623127108/archive/2010/07/21/5753290.aspx
winform的 看看吧或许有用
IT修补匠 2010-07-23
  • 打赏
  • 举报
回复
使用fileupload控件

乔木 2010-07-21
  • 打赏
  • 举报
回复
csdn上的下载资源可是很多的哟,
lanfengsese 2010-07-21
  • 打赏
  • 举报
回复
 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>");
}
段传涛 2010-07-21
  • 打赏
  • 举报
回复
项目源码 我有几个
你现看看这个不行 我再发给你
http://www.51aspx.com/CV/uploaddown/
Valefish 2010-07-21
  • 打赏
  • 举报
回复
VS上的控件就能实现 你的问题啊 多看看MSDN吧
mayonglong 2010-07-21
  • 打赏
  • 举报
回复
网上应该很多,不过不知道lz说的是Web还是WinForm~~
zjx198934 2010-07-21
  • 打赏
  • 举报
回复
如果想实现真进度条的话,建议使用flash或者activeX,否则就算用的是StreamReader读取到流,在分块存到目录的操作都是做无用功,无非是先将数据读到了服务器的内存中,再从内存中写文件(测已试过)。
sunboyyun 2010-07-21
  • 打赏
  • 举报
回复
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();

}
}

}
machunjie2003 2010-07-21
  • 打赏
  • 举报
回复
#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
jellyjojo 2010-07-21
  • 打赏
  • 举报
回复
下载

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));

}
}
}
}
eastzheng1 2010-07-21
  • 打赏
  • 举报
回复
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>
红色表示上传的文件大小
Love_Air523824 2010-07-21
  • 打赏
  • 举报
回复
//文件上传
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());
}
}
Love_Air523824 2010-07-21
  • 打赏
  • 举报
回复
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()); } } }}
huminghua 2010-07-21
  • 打赏
  • 举报
回复
同意楼上的!嘿嘿!
huwen7565833 2010-07-21
  • 打赏
  • 举报
回复
[Quote=引用 8 楼 computerfox 的回复:]
google搜索,首先要确定你的winform还是asp.net?
[/Quote]
网页版的肯定是Asp.NET的 啊!!
捷哥1999 2010-07-20
  • 打赏
  • 举报
回复
google搜索,首先要确定你的winform还是asp.net?
zjx198934 2010-07-20
  • 打赏
  • 举报
回复
上传

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();
}


jsmouse 2010-07-20
  • 打赏
  • 举报
回复
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);
}
}
加载更多回复(4)

110,561

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

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