Having troubles calling a Controller Post Method

前端 未结 1 1202
眼角桃花
眼角桃花 2020-11-30 13:42

Here\'s my method

    [AcceptVerbs(HttpVerbs.Post)]
    public void SaveImage(FormCollection formValues)
    {
        byte[] contents = Convert.FromBase64St         


        
相关标签:
1条回答
  • 2020-11-30 13:57

    I had a [lot] of trouble with this and I used this in the end;

    View:

    <% using (Html.BeginForm( "PhotoAdd", "Photos", FormMethod.Post, new { enctype = "multipart/form-data" }))   { %>
    
    <input type="file" id="file" name="file" class="field" style="width:300px;"/>
    
    <%} %>
    

    Controller:

    var file = Request.Files["file"];
    byte[] buf = new byte[file.ContentLength];
    file.InputStream.Read(buf, 0, file.ContentLength);
    

    I'm not sure whether this is what you are looking for but like I said I have a lot of problems allowing my users to upload a photo of themselves in my web site.

    Basically I have a View which contains a field of type "file" on it and a "Submit" button for the post back event.

    Then in the controller I have the following;

        [AcceptVerbs( HttpVerbs.Post ), Authorize]
        public ActionResult PhotoAdd(FormCollection collection)
        {
            try
            {
                var file = Request.Files["file"];
    
                byte[] buf = new byte[file.ContentLength];
                file.InputStream.Read(buf, 0, file.ContentLength);
    

    The difficulty I ran into was getting the controller to get the request along with the file name and path. Once I had that I could convert the file to an array of bytes that I could then save to a SQL Database and an Image field.

    The one biggest thing I was missing was the Form method in the View which needs to read

    <% using (Html.BeginForm( "PhotoAdd", "Photos", FormMethod.Post, new { enctype = "multipart/form-data" }))   { %>
    

    The enctype allows you to pick up the filename and path of the selected file and for the controller to be able to grab the inputstream. Without it I found that either Request.Files was empty or that it only contained the file name and hence could not open it.

    Once you have saved the image to your database, displaying it is a doddle.

    I hope this answers your question.

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