如何使用带有asp.net 4.0的Web客户端将文件发送到另一个网页 [英] how to send files to another web page using web client with asp.net 4.0

查看:78
本文介绍了如何使用带有asp.net 4.0的Web客户端将文件发送到另一个网页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题,无法将文件内容发布到另一个网页.这是我的代码:

i have one issue for posting file content to another web page. here is my code:

Dim postData As String = "name=NAME2&dob=21/09/1991&add1=ADD11&add2=ADD22&city=CITY2&area=AREA2&state=STATE2&emailID=EMAILID2&Pin=380008&mobile=1234567890&IsNRI=False&stateId=1&categoryId=1&CategoryName=Test&FilePath=D:%9%SHALIN%9%HOW TO INSTALL WEBSITE TO IIS.docx"
        Dim tempCookies As New CookieContainer
        Dim encoding As New UTF8Encoding
        Dim byteData As Byte() = encoding.GetBytes(postData)
        Dim postReq As HttpWebRequest = DirectCast(WebRequest.Create("http://localhost:29478/AddressBook/Default.aspx"), HttpWebRequest)
        postReq.Method = "POST"
        postReq.KeepAlive = True
        postReq.CookieContainer = tempCookies
        postReq.ContentType = "multipart/form-data"
        postReq.Referer = "http://localhost:29478/AddressBook/Default.aspx"
        postReq.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2"
        postReq.ContentLength = byteData.Length
        postReq.UseDefaultCredentials = True
        postReq.PreAuthenticate = True
        postReq.Credentials = CredentialCache.DefaultCredentials
        'Dim status As Boolean = True
        'status = System.IO.File.Exists("D:\SHALIN\HOW TO INSTALL WEBSITE TO IIS.docx")
        'If status = True Then
        '    Console.WriteLine("Exists")
        'Else
        '    Console.WriteLine("Not Exists")
        'End If
        Dim wc As WebClient
        wc = New WebClient
        wc.UseDefaultCredentials = True
        wc.Credentials = CredentialCache.DefaultCredentials
        wc.Headers.Add("user-agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2")
        'wc.Headers.Add("Content-Disposition: form-data; name='files'; filename='HOW TO INSTALL WEBSITE TO IIS.docx'")
        wc.UploadFile(DirectCast(New Uri("http://localhost:29478/AddressBook/UploadFiles"), Uri), "PUT", "D:\SHALIN\HOW TO INSTALL WEBSITE TO IIS.docx")
        wc.Dispose()
        Dim postreqstream As Stream = postReq.GetRequestStream()
        postreqstream.Write(byteData, 0, byteData.Length)
        postreqstream.Close()
        Dim postresponse As HttpWebResponse
        postresponse = DirectCast(postReq.GetResponse(), HttpWebResponse)
        tempCookies.Add(postresponse.Cookies)
        logincookie = tempCookies
        Dim postreqreader As New StreamReader(postresponse.GetResponseStream())
        Dim thepage As String = postreqreader.ReadToEnd

在页面接收器中,我有以下代码:

and at page receiver i have this code :

protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            pnlGrid.Visible = true;
            pnlEntry.Visible = false;
            pnlReport.Visible = false;
            GridView1.DataBind();
        }
        string name = null, dob = null, add1 = null, add2 = null, city = null, area = null, state = null, emailID = null, Pin = null, Mobile = null, IsNRI = null, stateId = null, categoryId = null, categoryname = null, FilePath = null;
        name = Request.Form["name"];
        dob = Request.Form["dob"];
        add1 = Request.Form["add1"];
        add2 = Request.Form["add2"];
        city = Request.Form["city"];
        area = Request.Form["area"];
        state = Request.Form["state"];
        emailID = Request.Form["emailID"];
        Pin = Request.Form["Pin"];
        Mobile = Request.Form["mobile"];
        IsNRI = Request.Form["IsNRI"];
        stateId = Request.Form["stateId"];
        categoryId = Request.Form["categoryId"];
        categoryname = Request.Form["CategoryName"];
        FilePath = Request.Form["FilePath"];
        if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(dob) && !string.IsNullOrEmpty(add1) && !string.IsNullOrEmpty(add2) && !string.IsNullOrEmpty(city) && !string.IsNullOrEmpty(area) && !string.IsNullOrEmpty(state) && !string.IsNullOrEmpty(emailID) && !string.IsNullOrEmpty(Pin) && !string.IsNullOrEmpty(Mobile) && !string.IsNullOrEmpty(IsNRI) && !string.IsNullOrEmpty(state) && !string.IsNullOrEmpty(categoryId) && !string.IsNullOrEmpty(categoryname) && !string.IsNullOrEmpty(FilePath))
        {
            using (DataClassesDataContext db = new DataClassesDataContext())
            {
                bool IsNrI = false;
                if (IsNRI.Equals("True"))
                {
                    IsNrI = true;
                }
                else
                {
                    IsNrI = false;
                }
                ADD myAdd = new ADD();
                myAdd.Name = name;
                myAdd.Dob = DateTime.ParseExact(dob, "dd/MM/yyyy", null);
                myAdd.Add1 = add1;
                myAdd.Add2 = add2;
                myAdd.City = city;
                myAdd.Area = area;
                myAdd.State = state;
                myAdd.Pin = Pin;
                myAdd.Mobile = Mobile;
                myAdd.EmailID = emailID;
                myAdd.IsNRI = IsNrI;
                myAdd.StateId = int.Parse(stateId);
                myAdd.CategoryID = int.Parse(categoryId);
                myAdd.CategoryName = categoryname;
                db.ADDs.InsertOnSubmit(myAdd);
                db.SubmitChanges();
                int newId = myAdd.TabId;
                if (newId > 0)
                {
                    pnlGrid.Visible = true;
                    pnlEntry.Visible = false;
                    GridView1.DataBind();
                    Literal2.Text = "Record Inserted Successfully!";
                    UpdatePanel1.Update();
                }
            }
            FileUpload1.SaveAs(Server.MapPath("~/UploadFiles/" + Request.Files["files"].FileName));
        }
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
    }

在这里,我无法从Web客户端接收文件.我该怎么办?

here i can't receive file from web client. what can i do?

*************更新了****************

*************Updated****************

wc.UploadFile(DirectCast(New Uri("http://localhost:29478/AddressBook/UploadFiles"), Uri), "POST", "D:\SHALIN\HOW TO INSTALL WEBSITE TO IIS.docx")


The underlying connection was closed: An unexpected error occurred on a receive.

第二把戏:

 Dim wc As WebClient
            wc = New WebClient
            wc.UseDefaultCredentials = True
            wc.Credentials = CredentialCache.DefaultCredentials
            wc.Headers.Add("user-agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2")
            wc.UploadFileAsync(DirectCast(New Uri("http://localhost:29478/AddressBook/UploadFiles"), Uri), "POST", "D:\SHALIN\HOW TO INSTALL WEBSITE TO IIS.docx")
            wc.Dispose()

此代码如何正常运行,但无法在aspx页面上获取文件

How ever this code works fine but not getting file at aspx page

        foreach (string f in Request.Files.AllKeys)
        {
            HttpPostedFile file = Request.Files[f];
            file.SaveAs(Server.MapPath("~/UploadFiles/" + file.FileName));
        }

推荐答案

这是一个非常简化的代码段,显示了如何将文件发送到网页:

Here is a very simplified code piece which shows how to send a file to a webpage:

用于发送的C#

WebClient myWebClient = new WebClient();

string fileName = "path to file 2 send";
string uriString = "url asp page 2 receive";

byte[] responseArray = myWebClient.UploadFile(uriString,fileName);

ASP.NET页面

<%@ Import Namespace="System"%>
<%@ Import Namespace="System.IO"%>
<%@ Import Namespace="System.Net"%>
<%@ Import NameSpace="System.Web"%>

<Script language="C#" runat=server>
void Page_Load(object sender, EventArgs e) {

    foreach(string f in Request.Files.AllKeys) {
        HttpPostedFile file = Request.Files[f];
        file.SaveAs("c:\\inetpub\\test\\UploadedFiles\\" + file.FileName);
    }   
}

</Script>
<html>
<body>
<p> Upload complete.  </p>
</body>
</html>

Src: https://msdn.microsoft.com/en-us/library/36s52zhs(v = vs.110).aspx

这篇关于如何使用带有asp.net 4.0的Web客户端将文件发送到另一个网页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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