File Upload ASP.NET MVC 3.0

后端 未结 21 1272
无人共我
无人共我 2020-11-22 01:09

(Preface: this question is about ASP.NET MVC 3.0 which was released in 2011, it is not about ASP.NET Core 3.0 which was released in 2019)

I want to

21条回答
  •  执笔经年
    2020-11-22 01:57

    How i do mine is pretty much as above ill show you my code and how to use it with a MYSSQL DB...

    Document table in DB -

    int Id ( PK ), string Url, string Description, CreatedBy, TenancyId DateUploaded

    The above code ID, being the Primary key, URL being the name of the file ( with file type on the end ), file description to ouput on documents view, CreatedBy being who uploaded the file, tenancyId, dateUploaded

    inside the view you must define the enctype or it will not work correctly.

    @using (Html.BeginForm("Upload", "Document", FormMethod.Post, new { enctype = "multipart/form-data" }))
    {
    
    }

    The above code will give you the browse button, then inside my project I have a class basically called IsValidImage which just checks the filesize is under your specified max size, checks if its an IMG file, this is all in a class bool function. So if true returns true.

    public static bool IsValidImage(HttpPostedFileBase file, double maxFileSize, ModelState ms )
    {
        // make sur the file isnt null.
        if( file == null )
            return false;
    
    // the param I normally set maxFileSize is 10MB  10 * 1024 * 1024 = 10485760 bytes converted is 10mb
    var max = maxFileSize * 1024 * 1024;
    
    // check if the filesize is above our defined MAX size.
    if( file.ContentLength > max )
        return false;
    
    try
    {
        // define our allowed image formats
        var allowedFormats = new[] { ImageFormat.Jpeg, ImageFormat.Png, ImageFormat.Gif, ImageFormat.Bmp };
    
        // Creates an Image from the specified data stream.      
        using (var img = Image.FromStream(file.InputStream))
        {
            // Return true if the image format is allowed
            return allowedFormats.Contains(img.RawFormat);
        }
    }
    catch( Exception ex )
    {
        ms.AddModelError( "", ex.Message );                 
    }
    return false;   
    }
    

    So in the controller:

    if (!Code.Picture.IsValidUpload(model.File, 10, true))
    {                
        return View(model);
    }
    
    // Set the file name up... Being random guid, and then todays time in ticks. Then add the file extension
    // to the end of the file name
    var dbPath = Guid.NewGuid().ToString() + DateTime.UtcNow.Ticks + Path.GetExtension(model.File.FileName);
    
    // Combine the two paths together being the location on the server to store it
    // then the actual file name and extension.
    var path = Path.Combine(Server.MapPath("~/Uploads/Documents/"), dbPath);
    
    // set variable as Parent directory I do this to make sure the path exists if not
    // I will create the directory.
    var directoryInfo = new FileInfo(path).Directory;
    
    if (directoryInfo != null)
        directoryInfo.Create();
    
    // save the document in the combined path.
    model.File.SaveAs(path);
    
    // then add the data to the database
    _db.Documents.Add(new Document
    {
        TenancyId = model.SelectedTenancy,
        FileUrl = dbPath,
        FileDescription = model.Description,
        CreatedBy = loggedInAs,
        CreatedDate = DateTime.UtcNow,
        UpdatedDate = null,
        CanTenantView = true
    });
    
    _db.SaveChanges();
    model.Successfull = true;
    

提交回复
热议问题