简体   繁体   中英

upload file asp.net mvc 2

i am trying to execute a task after uploading a file. After the task is finished i would like to display some info. At the moment i have an Upload action that will fire after clicking the 'Do task' button which is not good. question :I would like to just trigger the 'Sometask' action and not the Uploadaction?

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<%= Html.BeginForm("Upload","Home",FormMethod.Post,new { enctype = "multipart/form-data" }) %>
<%{ %>
<%=Html.HiddenFor(model=>model.Filepath) %>
<input type="file" id="upload" name="upload" />
<button id="btnUpload">
    upload</button>
<%} %>
<button id="btnTask">
    Do Task</button>
<script type="text/javascript">
    $(document).ready(function (event) {
        $('#btnTask').click(function () {
            $.post("/Home/Sometask",
            { filePath: $("#Filepath").val() },
             function (data) {
                alert(data);
            });
            event.preventDefault;
        });
    });

</script>

    [HttpPost]
    public ActionResult Upload()
    {
        HttpPostedFileBase selectedFile = Request.Files["upload"];

        if (selectedFile.ContentLength > 0)
        {
            string filePath = Path.Combine(HttpContext.Server.MapPath("\\Uploads\\")
            , Path.GetFileName(selectedFile.FileName));
            selectedFile.SaveAs(filePath);
            UploadModel model = new UploadModel();
            model.Filepath = filePath;
            return View("Index", model);
        }

        return View("Index");
    }

    public string Sometask(string Filepath)
    {
        Thread.Sleep(5000);
        return "ready";
    }

Is the Upload() method being called? Looking at the code, I would expect the Sometask() to be called but not the Upload() method. The jQuery code is calling .post when the button is clicked and that should eliminate the normal form posting. If Sometask() is not getting called, you many need to add [HttpPost] attribute to the Sometask() method.

Note that for security reasons files cannot be uploaded from Javascript.

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