使用HttpWebRequest在C#中上传文件 [英] upload file in c# with HttpWebRequest

查看:87
本文介绍了使用HttpWebRequest在C#中上传文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好我在服务器上上传pdf文件时遇到问题.我使用HttpWebRequest和HTTP的POST方法
这是我的代码:

Hi guys. I''ve a problem with the upload of pdf file on the server.I use HttpWebRequest and POST method of HTTP
This is my code:

string[] open = this.openFileDialog1.FileName.Split(''\\'');
           string nome = open[open.Length - 1];
           string[] temp = nome.Split(''.'');
           string extension = temp[1];
           HttpWebRequest req = (HttpWebRequest)WebRequest.Create(this.indirizzo + "servletUpload/controllerFiles");
           string post_data = this.openFileDialog1.FileName;
           string boundary = "AaB03x";
           string useragent = "_Webclient_Meetecho 1.0";
           req.UserAgent = useragent;

           req.ContentType = "multipart/form-data; boundary=" + boundary;
           req.Method = "POST";
           byte[] contents = FileToByteArray(post_data);
           MemoryStream postData = new MemoryStream();
           string newLine = "\r\n";
           StreamWriter sw = new StreamWriter(postData);
           sw.Write("--" + boundary + newLine);
           sw.Write("Content-Disposition: form-data; name=\"myFile\"" +"; filename=" + "\"" +  this.stanza + "-" + this.room + "."+extension + "\"" + newLine,"upload",this.openFileDialog1.FileName, newLine);
           sw.Write("Content-Type: application/octet-stream; charset=ISO-8859-1" + newLine);
           sw.Write("Content-Transfer-Encoding: binary" + newLine + newLine);
           sw.Write("VALUE" + newLine);
           sw.Write("--{0}--{1}", boundary, newLine);

           sw.Flush();


           postData.Write(contents, 0, contents.Length);
           sw.Write(newLine);


           sw.Flush();

           req.ContentLength = postData.Length;
           using (Stream s = req.GetRequestStream())

               postData.WriteTo(s);

          postData.Close();



FileToByteArray将文件转换为字节数组.
我收到内部服务器错误

如果我失败了?



FileToByteArray convert the file in a byte array.
I receive an internal server error

Where i fail???

推荐答案

您是否可以设置一个断点(或以其他方式验证该帖子是否已发布到您的服务器端代码中)?如果不是,那么您发布的文件可能大于Web服务器的maxRequestLength吗?

**编辑**刚注意到您正在针对Java服务器-忽略maxRequestLength属性,即.NET. (尽管可能类似),您需要在服务器端找出错误所在,然后才能在此处获得任何有用的答复.
Are you able to put a break point (or otherwise validate that the post is making it to your server-side code)? If not, then maybe the file you''re posting is larger than the maxRequestLength for your web server?

** EDIT ** just noticed you''re targeting a java server - so ignore maxRequestLength attribute, that''s .NET. (Could be something similar though) You''ll need to find out what the error is on the server-side before you can get any useful replies here.


这篇关于使用HttpWebRequest在C#中上传文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆