How to restrict certain file extensions and save to the database?

2

I need to upload images to my database and use the data type as Bytes in the SQL Server database.

How do I guarantee that it really would be an image that will be passing to him? I want to leave released only for .jpeg and .png files. Is it possible to do this?

How do I integrate the input HTML to get the file via C #?

    
asked by anonymous 10.02.2014 / 20:23

1 answer

3

For the browser to list only image files you can do this:

<input type="file" name="file" accept="image/jpg, image/png">

However, you will also need to do a validation on the Controller, assuming the signature of your method looks something like this:

[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
    string extensao = Path.GetExtension(file.FileName);
    string[] extensoesValidas = new string[] { "jpg", "png" };

    if (!extensoesValidas.Contains(extensao))
        new HttpException(string.Format("Extensão de arquivo *.{0} não suportada", extensao));

    var img = Image.FromStream(file.InputStream);

    //código para salvar a imagem no banco
}

You can still test ContentType to ensure greater efficiency:

string[] contentTypes = new string[] { "image/jpg", "image/png" };
if (!contentTypes.Contains(file.ContentType))
{
    //código para mensagem de erro
}

List of ContentTypes .

    
10.02.2014 / 20:36