How to cast string to HttpFilePostedBase

2019-08-18 03:01发布

问题:

Is there a way how to convert the string to HttpFilePostedBase? I'm currently using the Ajax File upload . But the value that it return is string. But my method is requesting for HttpFilePostedBase is there a way how to cast or convert it to HttpFilePostedBase?

here's my sample method in uploading files.

public bool uploadfiles(HttpPostedFileBase filedata)
{
bool status = false;
//code for uploading goes here
return status;
}

How can i call this method if the ajax file upload is passing a string?

回答1:

Are you using IE or Chrome/Firefox? cause, different browsers upload files in a different manner. IE uploads the files through Requres.Files but others use qqfile in the query string. Take a look here on how to use valums with mvc for different browsers

EDIT: Okay then, how about this. This is an example which worked for me:

        public void ControllerUploadHandler()
    {
        // Set the response return data type
        this.Response.ContentType = "text/html";

        try
        {
            // get just the original filename
            byte[] buffer = new byte[Request.ContentLength];
            if (Request.QueryString["qqfile"] != null)
            {
                using (BinaryReader br = new BinaryReader(this.Request.InputStream))
                    br.Read(buffer, 0, buffer.Length);
            }
            else if (Request.Files.Count > 0)
            {
                HttpPostedFileBase httpPostedFileBase = Request.Files[0] as HttpPostedFileBase;
                using (BinaryReader br = new BinaryReader(httpPostedFileBase.InputStream))
                    br.Read(buffer, 0, buffer.Length);
            }
            else
                this.Response.Write(" {'success': false }");

            // return the json object as successful
            this.Response.Write("{ 'success': true }");
            this.Response.End();
            return;
        }
        catch (Exception)
        {
            // return the json object as unsuccessful
            this.Response.Write("{ 'success': false }");
            this.Response.End();
        }
    }


回答2:

You can't. You can access files posted to an aspx page via the HttpContext.Request.Files property.