locked
Fetching form data and obtaining response RRS feed

  • Question

  • User-560223997 posted

    I am writing an app that allows one to upload several files and that has a table in the view dinamically updated according to the uploading.

    Thus, I have a view with a form like this:

    <form id="AddAttachmentFrm" enctype="multipart/form-data" onsubmit="afFileSubmitAjax(this); return false;" >
    ...
        <input type="submit" id="AddAttachment" name="AddAttachment" class="btn btn-primary" value="Upload" />
    ...
    </form>
    

    The form submission triggers the following JavaScript method:

            async function afFileSubmitAjax(oFormElem) {
                const formData = new FormData(oFormElem);
    
                var response = await fetch("@Url.Action("PostFile","Home")", {
                    method: 'POST',
                    body: formData
                });
    

    My controller contains the following function which deals with /Home/PostFile:

            [HttpPost]
            public JsonResult PostFile(IFormCollection form)
            {
                string id = "Error";
    
                try
                {
                    IFormFile file = form.Files[0];
                    string filename = Path.GetFileName(file.FileName);
    
                    if (file.Length > 1048576)
                        return Json(String.Empty);
                    
                    FileCacheModel fcitem = AddTempFile(filename, file, comment);
    
                    id = fcitem.id; // an unique id
    
                    AddFileToDatabase(fcitem);
                }
                catch
                {
                    return Json(String.Empty);
                }
    
                return Json(id);
            }

    Now I would like to obtain the information that comes in the end of the function (return Json(id)). How can I accomplished that? 

    I tried to see the variable response of the JavaScript snippet, and I can't find the information the method returns.

    Could you help me?

    Tuesday, March 24, 2020 3:08 PM

Answers

  • User-474980206 posted

    to see the response data, use the browser debugger. look at the network trace.

    in the javascript, fetch returns a response object. you need to process body stream to see the data (as yours is json):

          var response = await fetch("@Url.Action("PostFile","Home")", {
                    method: 'POST',
                    body: formData
                });
    
          // read response stream
          if (!response.ok) {
            alert("bad response: " + response.statusText); 
            return;
          }       
          var data = await response.json();
          

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, March 24, 2020 3:46 PM