简体   繁体   中英

How to capture file upload data from web page external to an ASP.NET site using .NET

I'm well aware of how to get files from the client to the server using standard ASP.NET techniques, however, I have a need to be able to retrieve data from a third party web page written in basic html and process the file data in an asp.net web application.

So if the basic html looks like this...

<form id="form1" action="WebForm.aspx" method="post">

        <input name="fileUpload1" type="file" enctype="multipart/form-data" />

        <input type="submit" value="click" />

    </form>

How do I retrieve the file data in the page referenced in the action attribute of the form. So far I have tried the code below, which allows me to access the file name - but not the byte stream of the file.

protected void Page_Load( object sender, EventArgs e )
        {
            string fileName = Request.Form["fileUpload1"];

            // No files appear in the request.files collection in code below.

            foreach (string file in Request.Files)
            {
                HttpPostedFile hpf = Request.Files[file] as HttpPostedFile;
                if (hpf.ContentLength == 0)
                    continue;
                string savedFileName = Path.Combine(
                   AppDomain.CurrentDomain.BaseDirectory,
                   Path.GetFileName( hpf.FileName ) );
                hpf.SaveAs( savedFileName );
            }
        }

Any advice much appreciated.

Your form is incorrect. The enctype parameter should be on the form tag:

<form id="form1" action="WebForm.aspx" method="post" enctype="multipart/form-data">
    <input name="fileUpload1" type="file" />
    <input type="submit" value="click" />
</form>

If you're trying to retrieve a file or resource from a remote (third-party) server during your Page_Load code, you don't need to use a file upload form.

Try this instead:

protected void Page_Load(object sender, EventArgs e) {

    using(WebClient client = new WebClient()) {
        var html = client.DownloadString("http://www.google.com/");
        File.WriteAllText("filename", html);
    }
}

Since this is not a ASP.NET form and you have no control over it, you will need to use a 3rd party component like Softartisans FileUp . I am sure there are other controls like it. A few others are mentioned on the Learn More about Uploading Files! page.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM