locked
Uploading a file using webapi C# RRS feed

  • Question

  • User995576430 posted

    I have issues uploading a file using webapi C#.
    The "System.Web.HttpContext.Current.Request.Files" always returns zero.
    Any guess on where i am going wrong.

    ---------------------------------------------------------------------------------------------------------
    .ASPX CODE :
    ---------------------------------------------------------------------------------------------------------
    <body>
        <form id="form1" runat="server" enctype="multipart/form-data">
        <div>
            <input id="MyFile" type="file" size="66" accept="html" runat="server" name="MyFile">
            <input type="button" onclick="fntest()" />
        </div>
        </form>
    </body>
    ---------------------------------------------------------------------------------------------------------
    WEBAPI CALL:
    ---------------------------------------------------------------------------------------------------------
    <script type="text/javascript">
    
            var fntest = function () {
                var inputdata = {
                    Action: 'TEST'
                };
                var objRequest = { RequestType: "ApiHello", RequestInput: inputdata, ResponseType: 'HTML' };
                queryJsonDataTest("Test/ApiHello",
                   "POST",
                   function (data) {
                       var objData = JSON.parse(data).ResponseOutput;                   
                   },
                   JSON.stringify(objRequest));
            }
    </script>
    ---------------------------------------------------------------------------------------------------------
    TESTCONTROLLER.CS CODE:
    ---------------------------------------------------------------------------------------------------------
    System.Web.HttpFileCollection hfc = System.Web.HttpContext.Current.Request.Files;
    ---------------------------------------------------------------------------------------------------------

    Monday, October 3, 2016 7:23 AM

Answers

  • User-2057865890 posted

    Hi Xavier,

    You could add the uploaded file content to the form data collection.

    A working sample.

    UploadFile Page

    <!DOCTYPE html>
    <html>
    <head>
        <title></title>
        <meta charset="utf-8" />
        <script src="Scripts/jquery-1.10.2.min.js"></script>
    </head>
    <body>
        <form>
            <div>
                <label for="fileUpload" />
                Select File to Upload: <input id="fileUpload" type="file" />
    
                <input id="btnUploadFile" type="button" value="Upload File" />
            </div>
        </form>
    </body>
    </html>
    <script type="text/javascript">
        $(document).ready(function () {
    
            $('#btnUploadFile').on('click', function () {
    
                var data = new FormData();
    
                var files = $("#fileUpload").get(0).files;
    
                // Add the uploaded image content to the form data collection
                if (files.length > 0) {
                    data.append("UploadedImage", files[0]);
                }
    
                // Make Ajax request with the contentType = false, and procesDate = false
                $.ajax({
                    type: "POST",
                    url: "/api/file/uploadfile",
                    contentType: false,
                    processData: false,
                    data: data
                });
            });
        });
    </script>

    Controller

    public class FileController : ApiController
        {
            [HttpPost]
            public void UploadFile()
            {
                if (HttpContext.Current.Request.Files.AllKeys.Any())
                {
                    // Get the uploaded image from the Files collection
                    var httpPostedFile = HttpContext.Current.Request.Files["UploadedImage"];
    
                    if (httpPostedFile != null)
                    {
                        // Validate the uploaded image(optional)
    
                        // Get the complete file path
                        var fileSavePath = Path.Combine(HttpContext.Current.Server.MapPath("~/UploadedFiles"), httpPostedFile.FileName);
    
                        // Save the uploaded file to "UploadedFiles" folder
                        httpPostedFile.SaveAs(fileSavePath);
                    }
                }
            }
        }

    Best Regards,

    Chris

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, October 4, 2016 2:10 AM