File upload in MVC

前端 未结 2 1690
臣服心动
臣服心动 2020-12-30 13:21

I\'m trying to upload files within MVC. Most solution I saw on SO is use webform. I don\'t want to use that and personly prefer using streams. How do you implement RESTful f

相关标签:
2条回答
  • 2020-12-30 13:42
    public ActionResult register(FormCollection collection, HttpPostedFileBase FileUpload1){
    RegistrationIMG regimg = new RegistrationIMG();
    string ext = Path.GetExtension(FileUpload1.FileName);
    string path = Server.MapPath("~/image/");
    FileUpload1.SaveAs(path + reg.email + ext);
    regimg.Image = @Url.Content("~/image/" + reg.email + ext);
    db.SaveChanges();}
    
    0 讨论(0)
  • 2020-12-30 14:01

    Edit: And just when you think you have it all figured out you realise that there is a better way. Check out http://haacked.com/archive/2010/07/16/uploading-files-with-aspnetmvc.aspx

    Original: I am not sure that I understand your question 100%, but I assume that you want to upload a file to a url that looks something like http://{server name}/{Controller}/Upload? This would be implemented exactly like a normal file upload using web forms.

    So your controller has an action named upload and looks similar to this:

    //For MVC ver 2 use:
    [HttpPost]
    //For MVC ver 1 use:
    //[AcceptVerbs(HttpVerbs.Post)] 
    public ActionResult Upload()
    {
        try
        {
            foreach (HttpPostedFile file in Request.Files)
            {
                //Save to a file
                file.SaveAs(Path.Combine("C:\\File_Store\\", Path.GetFileName(file.FileName)));
    
                // * OR *
                //Use file.InputStream to access the uploaded file as a stream
                byte[] buffer = new byte[1024];
                int read = file.InputStream.Read(buffer, 0, buffer.Length);
                while (read > 0)
                {
                    //do stuff with the buffer
                    read = file.InputStream.Read(buffer, 0, buffer.Length);
                }
            }
            return Json(new { Result = "Complete" });
        }
        catch (Exception)
        {
            return Json(new { Result = "Error" });
        }
    }
    

    In this case I am returning Json to indicate success, but you can change this to xml (or anything for that matter) if needed.

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