File upload Jquery WebApi

后端 未结 2 1466
忘了有多久
忘了有多久 2020-12-03 08:12

I used this following code to upload file to server, but the file is not uploaded.

Html:

      
&l
相关标签:
2条回答
  • Instead of submit button can you try with normal button -

    <form enctype="multipart/form-data">
        <label>
            Using JQuery
        </label>
        <input name="file" type="file" id="me" />
        <input type="button" id="Upload" value="Upload" />
    </form>
    
    <script src="~/Scripts/jquery-1.10.2.min.js"></script>
    <script type="text/javascript">
        $(function () {
            $('#Upload').click(function () {
                var formData = new FormData();
                var opmlFile = $('#me')[0];
                formData.append("opmlFile", opmlFile.files[0]);
    
                $.ajax({
                    url: 'http://localhost:23133/api/file',
                    type: 'POST',
                    data: formData,
                    cache: false,
                    contentType: false,
                    processData: false
                });
            });
        });
    </script>
    

    Controller Action -

        public HttpResponseMessage Post()
        {
            HttpResponseMessage result = null;
            var httpRequest = HttpContext.Current.Request;
    
            // Check if files are available
            if (httpRequest.Files.Count > 0)
            {
                var files = new List<string>();
    
                // interate the files and save on the server
                foreach (string file in httpRequest.Files)
                {
                    var postedFile = httpRequest.Files[file];
                    var filePath = HttpContext.Current.Server.MapPath("~/" + postedFile.FileName);
                    postedFile.SaveAs(filePath);
    
                    files.Add(filePath);
                }
    
                // return result
                result = Request.CreateResponse(HttpStatusCode.Created, files);
            }
            else
            {
                // return BadRequest (no file(s) available)
                result = Request.CreateResponse(HttpStatusCode.BadRequest);
            }
    
            return result;
        }
    

    Output -

    enter image description here

    0 讨论(0)
  • 2020-12-03 08:55

    Your javascript isn't referencing the correct file input control.

    You need to change this var opmlFile = $('#opmlFile')[0];

    To this var opmlFile = $('#myFile')[0];

    0 讨论(0)
提交回复
热议问题