Socket的方式,在客户端获取文件流写入网络流,在传到服务端,在本机调试
一切正常,可以传输,从别的机器上传时,提示找不到文件,我想是创建文件流时
出错了,不知道哪位高手可以帮我在客户端创建文件流(文件为客户端文件)
18 个解决方案
#1
kk.PostedFile.InputStream()
用一个流直接读取,可以是内存流也可以是文件流,然后保存到一个字节数组中!
将字节数组做为参数传到command
用一个流直接读取,可以是内存流也可以是文件流,然后保存到一个字节数组中!
将字节数组做为参数传到command
#2
关注,学习!
#3
去孟子e章的homepage看看
#4
顶
#5
最好不要存再数据库里
if (File1.PostedFile!=null)
{
try
{
//int Len=0;
//string FileName="";
Image1.ImageUrl=File1.Value;
//Len=File1.Value.LastIndexOf(@"\");
//FileName=File1.Value.Substring(Len + 1);
// 文件另存
//File1.PostedFile.SaveAs(@"c:\temp\"+FileName);
// }
if (File1.PostedFile!=null)
{
try
{
//int Len=0;
//string FileName="";
Image1.ImageUrl=File1.Value;
//Len=File1.Value.LastIndexOf(@"\");
//FileName=File1.Value.Substring(Len + 1);
// 文件另存
//File1.PostedFile.SaveAs(@"c:\temp\"+FileName);
// }
#6
借题问一问: 怎么判断上传的图片大于100K就不给上传?
#7
再补(怎么我这样写不行呀???图才19K,但还是弹出这个限制来,不给上传,HELP):
if(files[0].ContentLength>400)
{
message.InnerHtml="上传的图片大小限定在100K以内!";
Page.RegisterStartupScript("","<script>alert('"+"注意:上传的图片大小限定在100K以内!"+"');</script>");
errorno=1;
}
if(files[0].ContentLength>400)
{
message.InnerHtml="上传的图片大小限定在100K以内!";
Page.RegisterStartupScript("","<script>alert('"+"注意:上传的图片大小限定在100K以内!"+"');</script>");
errorno=1;
}
#8
to:1122111
HttpPostedFile myFile = UploadFile.PostedFile;
//FileName.Text = myFile.FileName;
if(myFile.ContentLength > 102400)
{
Response.Write("<script language=javascript>");
Response.Write("alert('上传文件太大,系统限制最大为100K!');");
Response.Write("</script>");
return;
}
HttpPostedFile myFile = UploadFile.PostedFile;
//FileName.Text = myFile.FileName;
if(myFile.ContentLength > 102400)
{
Response.Write("<script language=javascript>");
Response.Write("alert('上传文件太大,系统限制最大为100K!');");
Response.Write("</script>");
return;
}
#9
晕,是这样呀,谢谢!!
#10
---------------------
基于http流上载:
---------------------
private void cmdSendFileData_Click(object sender, System.EventArgs e)
{
// This method takes a local file named datafile.txt and sends its
// contents via a WebRequest to a website. The contents are sent via
// HTTP using the Request stream of the WebRequest object. The file
// is accessed using a FileStream.
string strMsg = "In order to run this part of the sample, you must adjust the security settings" +
" for the physical directory that contains the ASPX files." + Environment.NewLine + Environment.NewLine +
"Please see the Readthis.htm file for more information." + Environment.NewLine +
"Also see the source code (for the procedure cmdSendFileData_Click) to remove this warning after the security settings have been adjusted.";
FileStream fs = null; //' To access the local file;
WebRequest req = null; //' Reference to the Webrequest;
// Wrap the stream access in a try {/Finally block to guarantee a timely
// release of the stream resources.
try
{
// Access the file
fs = new FileStream("..//..//DataFile.txt", FileMode.Open);
// Create the WebRequest instance
req = WebRequest.Create("http://localhost/SendAndReceiveDataWebPages/SendData.aspx");
// Use POST since we're sending content in the body.
req.Method = "POST";
// Copy from the file into the RequestStream
CopyData(fs, req.GetRequestStream());
}
catch( Exception exp)
{
MessageBox.Show(exp.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
finally
{
try
{
// Guarantee the streams will be closed
if (req != null) req.GetRequestStream().Close();
if (fs != null) fs.Close();
}
catch
{
// Eat the error if we get one
}
}
WebResponse rsp = null;
try
{
// This actually sends the data to the Web Server
rsp = req.GetResponse();
if (Convert.ToDouble(rsp.Headers["Content-Length"]) == 0)
{
MessageBox.Show("Data Sent Sucessfully.", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch( Exception exp)
{
MessageBox.Show(exp.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
try
{
if ( rsp != null) rsp.Close();
}
catch{
}
}
}
---------------------
基于http流下载:
---------------------
private void cmdReceiveDataFile_Click(object sender, System.EventArgs e)
{
// This method requests and receives an XML file from a website.
// The file is streamed back to this method, which copies the contents
// into a local file named ReceivedXMLFile.xml. The contents are streamed
// using the ResponseStream of the WebResponse class. The stream access
// is wrapped in try {/catch blocks to ensure timely release of the
// resources.
string strMsg = "In order to run this part of the sample, you must adjust the security settings" +
" for the physical directory that contains the ASPX files." + Environment.NewLine + Environment.NewLine +
"Please see the Readthis.htm file for more information." + Environment.NewLine +
"Also see the source code (for the procedure cmdReceiveImageFile_Click) to remove this warning after the security settings have been adjusted.";
FileStream fs = null; //' To access the local file;
WebRequest req;
StreamReader sr;
try
{
// This sets up the Request instance
req = WebRequest.Create("http://localhost/SendAndReceiveDataWebPages/ReceiveData.aspx");
// Use a GET since no data is being sent to the web server
req.Method = "GET";
// This causes the round-trip
WebResponse rsp = req.GetResponse();
try
{
// Open the file to stream in the content
fs = new FileStream("ReceivedFile.rar", FileMode.Create);
// Copy the content from the response stream to the file.
CopyData(rsp.GetResponseStream(), fs);
}
catch( Exception exp)
{
// Will catch any error that we're not explicitly trapping.
MessageBox.Show(exp.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Stop);
}
finally
{
// Guarantee the streams will be closed
if (rsp != null) rsp.GetResponseStream().Close();
if (fs != null) fs.Close();
}
MessageBox.Show("Receive of data file completed successfully!", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch( Exception exp)
{
// Will catch any error that we're not explicitly trapping.
MessageBox.Show(exp.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Stop);
}
}
--------------------------
方法:
--------------------------
private void CopyData(Stream FromStream, Stream ToStream)
{
// This routine copies content from one stream to another, regardless
// of the media represented by the stream.
// This will track the # bytes read from the FromStream
int intBytesRead;
// The maximum size of each read
const int intSize = 4096;
Byte[] bytes = new Byte[intSize];
// Read the first bit of content, then write and read all the content
// From the FromStream to the ToStream.
intBytesRead = FromStream.Read(bytes, 0, intSize);
while (intBytesRead > 0)
{
ToStream.Write(bytes, 0, intBytesRead);
intBytesRead = FromStream.Read(bytes, 0, intSize);
}
}
基于http流上载:
---------------------
private void cmdSendFileData_Click(object sender, System.EventArgs e)
{
// This method takes a local file named datafile.txt and sends its
// contents via a WebRequest to a website. The contents are sent via
// HTTP using the Request stream of the WebRequest object. The file
// is accessed using a FileStream.
string strMsg = "In order to run this part of the sample, you must adjust the security settings" +
" for the physical directory that contains the ASPX files." + Environment.NewLine + Environment.NewLine +
"Please see the Readthis.htm file for more information." + Environment.NewLine +
"Also see the source code (for the procedure cmdSendFileData_Click) to remove this warning after the security settings have been adjusted.";
FileStream fs = null; //' To access the local file;
WebRequest req = null; //' Reference to the Webrequest;
// Wrap the stream access in a try {/Finally block to guarantee a timely
// release of the stream resources.
try
{
// Access the file
fs = new FileStream("..//..//DataFile.txt", FileMode.Open);
// Create the WebRequest instance
req = WebRequest.Create("http://localhost/SendAndReceiveDataWebPages/SendData.aspx");
// Use POST since we're sending content in the body.
req.Method = "POST";
// Copy from the file into the RequestStream
CopyData(fs, req.GetRequestStream());
}
catch( Exception exp)
{
MessageBox.Show(exp.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
finally
{
try
{
// Guarantee the streams will be closed
if (req != null) req.GetRequestStream().Close();
if (fs != null) fs.Close();
}
catch
{
// Eat the error if we get one
}
}
WebResponse rsp = null;
try
{
// This actually sends the data to the Web Server
rsp = req.GetResponse();
if (Convert.ToDouble(rsp.Headers["Content-Length"]) == 0)
{
MessageBox.Show("Data Sent Sucessfully.", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch( Exception exp)
{
MessageBox.Show(exp.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
try
{
if ( rsp != null) rsp.Close();
}
catch{
}
}
}
---------------------
基于http流下载:
---------------------
private void cmdReceiveDataFile_Click(object sender, System.EventArgs e)
{
// This method requests and receives an XML file from a website.
// The file is streamed back to this method, which copies the contents
// into a local file named ReceivedXMLFile.xml. The contents are streamed
// using the ResponseStream of the WebResponse class. The stream access
// is wrapped in try {/catch blocks to ensure timely release of the
// resources.
string strMsg = "In order to run this part of the sample, you must adjust the security settings" +
" for the physical directory that contains the ASPX files." + Environment.NewLine + Environment.NewLine +
"Please see the Readthis.htm file for more information." + Environment.NewLine +
"Also see the source code (for the procedure cmdReceiveImageFile_Click) to remove this warning after the security settings have been adjusted.";
FileStream fs = null; //' To access the local file;
WebRequest req;
StreamReader sr;
try
{
// This sets up the Request instance
req = WebRequest.Create("http://localhost/SendAndReceiveDataWebPages/ReceiveData.aspx");
// Use a GET since no data is being sent to the web server
req.Method = "GET";
// This causes the round-trip
WebResponse rsp = req.GetResponse();
try
{
// Open the file to stream in the content
fs = new FileStream("ReceivedFile.rar", FileMode.Create);
// Copy the content from the response stream to the file.
CopyData(rsp.GetResponseStream(), fs);
}
catch( Exception exp)
{
// Will catch any error that we're not explicitly trapping.
MessageBox.Show(exp.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Stop);
}
finally
{
// Guarantee the streams will be closed
if (rsp != null) rsp.GetResponseStream().Close();
if (fs != null) fs.Close();
}
MessageBox.Show("Receive of data file completed successfully!", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch( Exception exp)
{
// Will catch any error that we're not explicitly trapping.
MessageBox.Show(exp.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Stop);
}
}
--------------------------
方法:
--------------------------
private void CopyData(Stream FromStream, Stream ToStream)
{
// This routine copies content from one stream to another, regardless
// of the media represented by the stream.
// This will track the # bytes read from the FromStream
int intBytesRead;
// The maximum size of each read
const int intSize = 4096;
Byte[] bytes = new Byte[intSize];
// Read the first bit of content, then write and read all the content
// From the FromStream to the ToStream.
intBytesRead = FromStream.Read(bytes, 0, intSize);
while (intBytesRead > 0)
{
ToStream.Write(bytes, 0, intBytesRead);
intBytesRead = FromStream.Read(bytes, 0, intSize);
}
}
#11
一个文件上传的类
namespace Wmj
{
public class MyUpload
{
private System.Web.HttpPostedFile postedFile=null;
private string savePath="";
private string extension="";
private int fileLength=0;
//显示该组件使用的参数信息
public string Help
{
get{
string helpstring;
helpstring="<font size=3>MyUpload myUpload=new MyUpload(); //构造函数";
helpstring+="myUpload.PostedFile=file1.PostedFile;//设置要上传的文件";
helpstring+="myUpload.SavePath=\"e:\\\";//设置要上传到服务器的路径,默认c:\\";
helpstring+="myUpload.FileLength=100; //设置上传文件的最大长度,单位k,默认1k";
helpstring+="myUpload.Extension=\"doc\";设置上传文件的扩展名,默认txt";
helpstring+="label1.Text=myUpload.Upload();//开始上传,并显示上传结果</font>";
helpstring+="<font size=3 color=red>Design By WengMingJun 2001-12-12 All Right Reserved!</font>";
return helpstring;
}
}
public System.Web.HttpPostedFile PostedFile
{
get
{
return postedFile;
}
set
{
postedFile=value;
}
}
public string SavePath
{
get
{
if(savePath!="") return savePath;
return "c:\\";
}
set
{
savePath=value;
}
}
public int FileLength
{
get
{
if(fileLength!=0) return fileLength;
return 1024;
}
set
{
fileLength=value*1024;
}
}
public string Extension
{
get
{
if(extension!="") return extension;
return "txt";
}
set
{
extension=value;
}
}
public string PathToName(string path)
{
int pos=path.LastIndexOf("\\");
return path.Substring(pos+1);
}
public string Upload()
{
if(PostedFile!=null)
{
try{
string fileName=PathToName(PostedFile.FileName);
if(!fileName.EndsWith(Extension)) return "You must select "+Extension+" file!";
if(PostedFile.ContentLength>FileLength) return "File too big!";
PostedFile.SaveAs(SavePath+fileName);
return "Upload File Successfully!";
}
catch(System.Exception exc)
{return exc.Message;}
}
return "Please select a file to upload!";
}
}
}
用csc /target:Library Wmj.cs 编译成dll供以后多次调用
调用举例
<%@page language="C#" runat="server"%>
<%@import namespace="Wmj"%>
<script language="C#" runat="server">
void Upload(object sender,EventArgs e)
{
MyUpload myUpload=new MyUpload();
// label1.Text=myUpload.Help;
myUpload.PostedFile=file1.PostedFile;
myUpload.SavePath="e:\\";
myUpload.FileLength=100;
label1.Text=myUpload.Upload();
}
</script>
<form enctype="multipart/form-data" runat="server">
<input type="file" id="file1" runat="server"/>
<asp:Button id="button1" Text="Upload" OnClick="Upload" runat="server"/>
<asp:Label id="label1" runat="server"/>
</form>
namespace Wmj
{
public class MyUpload
{
private System.Web.HttpPostedFile postedFile=null;
private string savePath="";
private string extension="";
private int fileLength=0;
//显示该组件使用的参数信息
public string Help
{
get{
string helpstring;
helpstring="<font size=3>MyUpload myUpload=new MyUpload(); //构造函数";
helpstring+="myUpload.PostedFile=file1.PostedFile;//设置要上传的文件";
helpstring+="myUpload.SavePath=\"e:\\\";//设置要上传到服务器的路径,默认c:\\";
helpstring+="myUpload.FileLength=100; //设置上传文件的最大长度,单位k,默认1k";
helpstring+="myUpload.Extension=\"doc\";设置上传文件的扩展名,默认txt";
helpstring+="label1.Text=myUpload.Upload();//开始上传,并显示上传结果</font>";
helpstring+="<font size=3 color=red>Design By WengMingJun 2001-12-12 All Right Reserved!</font>";
return helpstring;
}
}
public System.Web.HttpPostedFile PostedFile
{
get
{
return postedFile;
}
set
{
postedFile=value;
}
}
public string SavePath
{
get
{
if(savePath!="") return savePath;
return "c:\\";
}
set
{
savePath=value;
}
}
public int FileLength
{
get
{
if(fileLength!=0) return fileLength;
return 1024;
}
set
{
fileLength=value*1024;
}
}
public string Extension
{
get
{
if(extension!="") return extension;
return "txt";
}
set
{
extension=value;
}
}
public string PathToName(string path)
{
int pos=path.LastIndexOf("\\");
return path.Substring(pos+1);
}
public string Upload()
{
if(PostedFile!=null)
{
try{
string fileName=PathToName(PostedFile.FileName);
if(!fileName.EndsWith(Extension)) return "You must select "+Extension+" file!";
if(PostedFile.ContentLength>FileLength) return "File too big!";
PostedFile.SaveAs(SavePath+fileName);
return "Upload File Successfully!";
}
catch(System.Exception exc)
{return exc.Message;}
}
return "Please select a file to upload!";
}
}
}
用csc /target:Library Wmj.cs 编译成dll供以后多次调用
调用举例
<%@page language="C#" runat="server"%>
<%@import namespace="Wmj"%>
<script language="C#" runat="server">
void Upload(object sender,EventArgs e)
{
MyUpload myUpload=new MyUpload();
// label1.Text=myUpload.Help;
myUpload.PostedFile=file1.PostedFile;
myUpload.SavePath="e:\\";
myUpload.FileLength=100;
label1.Text=myUpload.Upload();
}
</script>
<form enctype="multipart/form-data" runat="server">
<input type="file" id="file1" runat="server"/>
<asp:Button id="button1" Text="Upload" OnClick="Upload" runat="server"/>
<asp:Label id="label1" runat="server"/>
</form>
#12
楼上的兄台,FromStream 是什么意思呀?
#13
FromStream是在哪个类的?? 我怎么引用不到呀
#14
using System.IO; //' Used to work with Streams;
using System.Net; //' Used for client-side of HTTP communication;
using System.Net; //' Used for client-side of HTTP communication;
#15
还是不行呀,我打FromStream. 之后弹不出来成员,怎么回事呀?
#16
FromStream就是一个Stream,我现在机子上面没装vs.net,也没有帮助。
你自己打开msdn帮助看看Stream类,是在那个名字空间下的,然后把它引入就行了。
我觉得是io,要不就是text
你自己打开msdn帮助看看Stream类,是在那个名字空间下的,然后把它引入就行了。
我觉得是io,要不就是text
#17
各位好汉 ,兄弟我需要的是无组件上传文件,我的客户端是Web页,在其他的机器*问页面时通过socket可以传递数据(字符串).FileStream 所获取的文件路径(如果是客户端的,错误提示找不到此文件,如果是服务端的,正常),换句话说FileStream 是在web站点起作用当下载到别的机器时就会出错。
十分感谢各位好汉。
十分感谢各位好汉。
#18
不管是 基于http流还是 stream 流,都的先获取文件流,现在的问题是如何获取文件流
郁闷中:
感谢各位好汉
郁闷中:
感谢各位好汉
#1
kk.PostedFile.InputStream()
用一个流直接读取,可以是内存流也可以是文件流,然后保存到一个字节数组中!
将字节数组做为参数传到command
用一个流直接读取,可以是内存流也可以是文件流,然后保存到一个字节数组中!
将字节数组做为参数传到command
#2
关注,学习!
#3
去孟子e章的homepage看看
#4
顶
#5
最好不要存再数据库里
if (File1.PostedFile!=null)
{
try
{
//int Len=0;
//string FileName="";
Image1.ImageUrl=File1.Value;
//Len=File1.Value.LastIndexOf(@"\");
//FileName=File1.Value.Substring(Len + 1);
// 文件另存
//File1.PostedFile.SaveAs(@"c:\temp\"+FileName);
// }
if (File1.PostedFile!=null)
{
try
{
//int Len=0;
//string FileName="";
Image1.ImageUrl=File1.Value;
//Len=File1.Value.LastIndexOf(@"\");
//FileName=File1.Value.Substring(Len + 1);
// 文件另存
//File1.PostedFile.SaveAs(@"c:\temp\"+FileName);
// }
#6
借题问一问: 怎么判断上传的图片大于100K就不给上传?
#7
再补(怎么我这样写不行呀???图才19K,但还是弹出这个限制来,不给上传,HELP):
if(files[0].ContentLength>400)
{
message.InnerHtml="上传的图片大小限定在100K以内!";
Page.RegisterStartupScript("","<script>alert('"+"注意:上传的图片大小限定在100K以内!"+"');</script>");
errorno=1;
}
if(files[0].ContentLength>400)
{
message.InnerHtml="上传的图片大小限定在100K以内!";
Page.RegisterStartupScript("","<script>alert('"+"注意:上传的图片大小限定在100K以内!"+"');</script>");
errorno=1;
}
#8
to:1122111
HttpPostedFile myFile = UploadFile.PostedFile;
//FileName.Text = myFile.FileName;
if(myFile.ContentLength > 102400)
{
Response.Write("<script language=javascript>");
Response.Write("alert('上传文件太大,系统限制最大为100K!');");
Response.Write("</script>");
return;
}
HttpPostedFile myFile = UploadFile.PostedFile;
//FileName.Text = myFile.FileName;
if(myFile.ContentLength > 102400)
{
Response.Write("<script language=javascript>");
Response.Write("alert('上传文件太大,系统限制最大为100K!');");
Response.Write("</script>");
return;
}
#9
晕,是这样呀,谢谢!!
#10
---------------------
基于http流上载:
---------------------
private void cmdSendFileData_Click(object sender, System.EventArgs e)
{
// This method takes a local file named datafile.txt and sends its
// contents via a WebRequest to a website. The contents are sent via
// HTTP using the Request stream of the WebRequest object. The file
// is accessed using a FileStream.
string strMsg = "In order to run this part of the sample, you must adjust the security settings" +
" for the physical directory that contains the ASPX files." + Environment.NewLine + Environment.NewLine +
"Please see the Readthis.htm file for more information." + Environment.NewLine +
"Also see the source code (for the procedure cmdSendFileData_Click) to remove this warning after the security settings have been adjusted.";
FileStream fs = null; //' To access the local file;
WebRequest req = null; //' Reference to the Webrequest;
// Wrap the stream access in a try {/Finally block to guarantee a timely
// release of the stream resources.
try
{
// Access the file
fs = new FileStream("..//..//DataFile.txt", FileMode.Open);
// Create the WebRequest instance
req = WebRequest.Create("http://localhost/SendAndReceiveDataWebPages/SendData.aspx");
// Use POST since we're sending content in the body.
req.Method = "POST";
// Copy from the file into the RequestStream
CopyData(fs, req.GetRequestStream());
}
catch( Exception exp)
{
MessageBox.Show(exp.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
finally
{
try
{
// Guarantee the streams will be closed
if (req != null) req.GetRequestStream().Close();
if (fs != null) fs.Close();
}
catch
{
// Eat the error if we get one
}
}
WebResponse rsp = null;
try
{
// This actually sends the data to the Web Server
rsp = req.GetResponse();
if (Convert.ToDouble(rsp.Headers["Content-Length"]) == 0)
{
MessageBox.Show("Data Sent Sucessfully.", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch( Exception exp)
{
MessageBox.Show(exp.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
try
{
if ( rsp != null) rsp.Close();
}
catch{
}
}
}
---------------------
基于http流下载:
---------------------
private void cmdReceiveDataFile_Click(object sender, System.EventArgs e)
{
// This method requests and receives an XML file from a website.
// The file is streamed back to this method, which copies the contents
// into a local file named ReceivedXMLFile.xml. The contents are streamed
// using the ResponseStream of the WebResponse class. The stream access
// is wrapped in try {/catch blocks to ensure timely release of the
// resources.
string strMsg = "In order to run this part of the sample, you must adjust the security settings" +
" for the physical directory that contains the ASPX files." + Environment.NewLine + Environment.NewLine +
"Please see the Readthis.htm file for more information." + Environment.NewLine +
"Also see the source code (for the procedure cmdReceiveImageFile_Click) to remove this warning after the security settings have been adjusted.";
FileStream fs = null; //' To access the local file;
WebRequest req;
StreamReader sr;
try
{
// This sets up the Request instance
req = WebRequest.Create("http://localhost/SendAndReceiveDataWebPages/ReceiveData.aspx");
// Use a GET since no data is being sent to the web server
req.Method = "GET";
// This causes the round-trip
WebResponse rsp = req.GetResponse();
try
{
// Open the file to stream in the content
fs = new FileStream("ReceivedFile.rar", FileMode.Create);
// Copy the content from the response stream to the file.
CopyData(rsp.GetResponseStream(), fs);
}
catch( Exception exp)
{
// Will catch any error that we're not explicitly trapping.
MessageBox.Show(exp.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Stop);
}
finally
{
// Guarantee the streams will be closed
if (rsp != null) rsp.GetResponseStream().Close();
if (fs != null) fs.Close();
}
MessageBox.Show("Receive of data file completed successfully!", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch( Exception exp)
{
// Will catch any error that we're not explicitly trapping.
MessageBox.Show(exp.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Stop);
}
}
--------------------------
方法:
--------------------------
private void CopyData(Stream FromStream, Stream ToStream)
{
// This routine copies content from one stream to another, regardless
// of the media represented by the stream.
// This will track the # bytes read from the FromStream
int intBytesRead;
// The maximum size of each read
const int intSize = 4096;
Byte[] bytes = new Byte[intSize];
// Read the first bit of content, then write and read all the content
// From the FromStream to the ToStream.
intBytesRead = FromStream.Read(bytes, 0, intSize);
while (intBytesRead > 0)
{
ToStream.Write(bytes, 0, intBytesRead);
intBytesRead = FromStream.Read(bytes, 0, intSize);
}
}
基于http流上载:
---------------------
private void cmdSendFileData_Click(object sender, System.EventArgs e)
{
// This method takes a local file named datafile.txt and sends its
// contents via a WebRequest to a website. The contents are sent via
// HTTP using the Request stream of the WebRequest object. The file
// is accessed using a FileStream.
string strMsg = "In order to run this part of the sample, you must adjust the security settings" +
" for the physical directory that contains the ASPX files." + Environment.NewLine + Environment.NewLine +
"Please see the Readthis.htm file for more information." + Environment.NewLine +
"Also see the source code (for the procedure cmdSendFileData_Click) to remove this warning after the security settings have been adjusted.";
FileStream fs = null; //' To access the local file;
WebRequest req = null; //' Reference to the Webrequest;
// Wrap the stream access in a try {/Finally block to guarantee a timely
// release of the stream resources.
try
{
// Access the file
fs = new FileStream("..//..//DataFile.txt", FileMode.Open);
// Create the WebRequest instance
req = WebRequest.Create("http://localhost/SendAndReceiveDataWebPages/SendData.aspx");
// Use POST since we're sending content in the body.
req.Method = "POST";
// Copy from the file into the RequestStream
CopyData(fs, req.GetRequestStream());
}
catch( Exception exp)
{
MessageBox.Show(exp.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
finally
{
try
{
// Guarantee the streams will be closed
if (req != null) req.GetRequestStream().Close();
if (fs != null) fs.Close();
}
catch
{
// Eat the error if we get one
}
}
WebResponse rsp = null;
try
{
// This actually sends the data to the Web Server
rsp = req.GetResponse();
if (Convert.ToDouble(rsp.Headers["Content-Length"]) == 0)
{
MessageBox.Show("Data Sent Sucessfully.", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch( Exception exp)
{
MessageBox.Show(exp.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
try
{
if ( rsp != null) rsp.Close();
}
catch{
}
}
}
---------------------
基于http流下载:
---------------------
private void cmdReceiveDataFile_Click(object sender, System.EventArgs e)
{
// This method requests and receives an XML file from a website.
// The file is streamed back to this method, which copies the contents
// into a local file named ReceivedXMLFile.xml. The contents are streamed
// using the ResponseStream of the WebResponse class. The stream access
// is wrapped in try {/catch blocks to ensure timely release of the
// resources.
string strMsg = "In order to run this part of the sample, you must adjust the security settings" +
" for the physical directory that contains the ASPX files." + Environment.NewLine + Environment.NewLine +
"Please see the Readthis.htm file for more information." + Environment.NewLine +
"Also see the source code (for the procedure cmdReceiveImageFile_Click) to remove this warning after the security settings have been adjusted.";
FileStream fs = null; //' To access the local file;
WebRequest req;
StreamReader sr;
try
{
// This sets up the Request instance
req = WebRequest.Create("http://localhost/SendAndReceiveDataWebPages/ReceiveData.aspx");
// Use a GET since no data is being sent to the web server
req.Method = "GET";
// This causes the round-trip
WebResponse rsp = req.GetResponse();
try
{
// Open the file to stream in the content
fs = new FileStream("ReceivedFile.rar", FileMode.Create);
// Copy the content from the response stream to the file.
CopyData(rsp.GetResponseStream(), fs);
}
catch( Exception exp)
{
// Will catch any error that we're not explicitly trapping.
MessageBox.Show(exp.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Stop);
}
finally
{
// Guarantee the streams will be closed
if (rsp != null) rsp.GetResponseStream().Close();
if (fs != null) fs.Close();
}
MessageBox.Show("Receive of data file completed successfully!", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch( Exception exp)
{
// Will catch any error that we're not explicitly trapping.
MessageBox.Show(exp.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Stop);
}
}
--------------------------
方法:
--------------------------
private void CopyData(Stream FromStream, Stream ToStream)
{
// This routine copies content from one stream to another, regardless
// of the media represented by the stream.
// This will track the # bytes read from the FromStream
int intBytesRead;
// The maximum size of each read
const int intSize = 4096;
Byte[] bytes = new Byte[intSize];
// Read the first bit of content, then write and read all the content
// From the FromStream to the ToStream.
intBytesRead = FromStream.Read(bytes, 0, intSize);
while (intBytesRead > 0)
{
ToStream.Write(bytes, 0, intBytesRead);
intBytesRead = FromStream.Read(bytes, 0, intSize);
}
}
#11
一个文件上传的类
namespace Wmj
{
public class MyUpload
{
private System.Web.HttpPostedFile postedFile=null;
private string savePath="";
private string extension="";
private int fileLength=0;
//显示该组件使用的参数信息
public string Help
{
get{
string helpstring;
helpstring="<font size=3>MyUpload myUpload=new MyUpload(); //构造函数";
helpstring+="myUpload.PostedFile=file1.PostedFile;//设置要上传的文件";
helpstring+="myUpload.SavePath=\"e:\\\";//设置要上传到服务器的路径,默认c:\\";
helpstring+="myUpload.FileLength=100; //设置上传文件的最大长度,单位k,默认1k";
helpstring+="myUpload.Extension=\"doc\";设置上传文件的扩展名,默认txt";
helpstring+="label1.Text=myUpload.Upload();//开始上传,并显示上传结果</font>";
helpstring+="<font size=3 color=red>Design By WengMingJun 2001-12-12 All Right Reserved!</font>";
return helpstring;
}
}
public System.Web.HttpPostedFile PostedFile
{
get
{
return postedFile;
}
set
{
postedFile=value;
}
}
public string SavePath
{
get
{
if(savePath!="") return savePath;
return "c:\\";
}
set
{
savePath=value;
}
}
public int FileLength
{
get
{
if(fileLength!=0) return fileLength;
return 1024;
}
set
{
fileLength=value*1024;
}
}
public string Extension
{
get
{
if(extension!="") return extension;
return "txt";
}
set
{
extension=value;
}
}
public string PathToName(string path)
{
int pos=path.LastIndexOf("\\");
return path.Substring(pos+1);
}
public string Upload()
{
if(PostedFile!=null)
{
try{
string fileName=PathToName(PostedFile.FileName);
if(!fileName.EndsWith(Extension)) return "You must select "+Extension+" file!";
if(PostedFile.ContentLength>FileLength) return "File too big!";
PostedFile.SaveAs(SavePath+fileName);
return "Upload File Successfully!";
}
catch(System.Exception exc)
{return exc.Message;}
}
return "Please select a file to upload!";
}
}
}
用csc /target:Library Wmj.cs 编译成dll供以后多次调用
调用举例
<%@page language="C#" runat="server"%>
<%@import namespace="Wmj"%>
<script language="C#" runat="server">
void Upload(object sender,EventArgs e)
{
MyUpload myUpload=new MyUpload();
// label1.Text=myUpload.Help;
myUpload.PostedFile=file1.PostedFile;
myUpload.SavePath="e:\\";
myUpload.FileLength=100;
label1.Text=myUpload.Upload();
}
</script>
<form enctype="multipart/form-data" runat="server">
<input type="file" id="file1" runat="server"/>
<asp:Button id="button1" Text="Upload" OnClick="Upload" runat="server"/>
<asp:Label id="label1" runat="server"/>
</form>
namespace Wmj
{
public class MyUpload
{
private System.Web.HttpPostedFile postedFile=null;
private string savePath="";
private string extension="";
private int fileLength=0;
//显示该组件使用的参数信息
public string Help
{
get{
string helpstring;
helpstring="<font size=3>MyUpload myUpload=new MyUpload(); //构造函数";
helpstring+="myUpload.PostedFile=file1.PostedFile;//设置要上传的文件";
helpstring+="myUpload.SavePath=\"e:\\\";//设置要上传到服务器的路径,默认c:\\";
helpstring+="myUpload.FileLength=100; //设置上传文件的最大长度,单位k,默认1k";
helpstring+="myUpload.Extension=\"doc\";设置上传文件的扩展名,默认txt";
helpstring+="label1.Text=myUpload.Upload();//开始上传,并显示上传结果</font>";
helpstring+="<font size=3 color=red>Design By WengMingJun 2001-12-12 All Right Reserved!</font>";
return helpstring;
}
}
public System.Web.HttpPostedFile PostedFile
{
get
{
return postedFile;
}
set
{
postedFile=value;
}
}
public string SavePath
{
get
{
if(savePath!="") return savePath;
return "c:\\";
}
set
{
savePath=value;
}
}
public int FileLength
{
get
{
if(fileLength!=0) return fileLength;
return 1024;
}
set
{
fileLength=value*1024;
}
}
public string Extension
{
get
{
if(extension!="") return extension;
return "txt";
}
set
{
extension=value;
}
}
public string PathToName(string path)
{
int pos=path.LastIndexOf("\\");
return path.Substring(pos+1);
}
public string Upload()
{
if(PostedFile!=null)
{
try{
string fileName=PathToName(PostedFile.FileName);
if(!fileName.EndsWith(Extension)) return "You must select "+Extension+" file!";
if(PostedFile.ContentLength>FileLength) return "File too big!";
PostedFile.SaveAs(SavePath+fileName);
return "Upload File Successfully!";
}
catch(System.Exception exc)
{return exc.Message;}
}
return "Please select a file to upload!";
}
}
}
用csc /target:Library Wmj.cs 编译成dll供以后多次调用
调用举例
<%@page language="C#" runat="server"%>
<%@import namespace="Wmj"%>
<script language="C#" runat="server">
void Upload(object sender,EventArgs e)
{
MyUpload myUpload=new MyUpload();
// label1.Text=myUpload.Help;
myUpload.PostedFile=file1.PostedFile;
myUpload.SavePath="e:\\";
myUpload.FileLength=100;
label1.Text=myUpload.Upload();
}
</script>
<form enctype="multipart/form-data" runat="server">
<input type="file" id="file1" runat="server"/>
<asp:Button id="button1" Text="Upload" OnClick="Upload" runat="server"/>
<asp:Label id="label1" runat="server"/>
</form>
#12
楼上的兄台,FromStream 是什么意思呀?
#13
FromStream是在哪个类的?? 我怎么引用不到呀
#14
using System.IO; //' Used to work with Streams;
using System.Net; //' Used for client-side of HTTP communication;
using System.Net; //' Used for client-side of HTTP communication;
#15
还是不行呀,我打FromStream. 之后弹不出来成员,怎么回事呀?
#16
FromStream就是一个Stream,我现在机子上面没装vs.net,也没有帮助。
你自己打开msdn帮助看看Stream类,是在那个名字空间下的,然后把它引入就行了。
我觉得是io,要不就是text
你自己打开msdn帮助看看Stream类,是在那个名字空间下的,然后把它引入就行了。
我觉得是io,要不就是text
#17
各位好汉 ,兄弟我需要的是无组件上传文件,我的客户端是Web页,在其他的机器*问页面时通过socket可以传递数据(字符串).FileStream 所获取的文件路径(如果是客户端的,错误提示找不到此文件,如果是服务端的,正常),换句话说FileStream 是在web站点起作用当下载到别的机器时就会出错。
十分感谢各位好汉。
十分感谢各位好汉。
#18
不管是 基于http流还是 stream 流,都的先获取文件流,现在的问题是如何获取文件流
郁闷中:
感谢各位好汉
郁闷中:
感谢各位好汉