簡體   English   中英

如何使用帶有asp.net 4.0的Web客戶端將文件發送到另一個網頁

[英]how to send files to another web page using web client with asp.net 4.0

我在將文件內容發布到另一個網頁時遇到一個問題。 這是我的代碼:

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

在頁面接收器中,我有以下代碼:

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客戶端接收文件。 我能做什么?

*************更新****************

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頁面上獲取文件

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

這是一個非常簡化的代碼段,顯示了如何將文件發送到網頁:

用於發送的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/zh-CN/library/36s52zhs( v = vs.110) .aspx

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM