How to restrict certain file extensions and save to database?

Asked

Viewed 2,918 times

2

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

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

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

  • Possibly this is from the file header. But you have two questions?

  • @Felipeavelar yes are two questions based on the same problem.

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 perform a validation in Controller, assuming your method signature is something like the following:

[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
}

It is still possible to test the 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 existing.

  • Great! Thanks! It will be of great help!

  • 1

    i made an edit, with a native method to get the file extension: Path.GetExtension()

Browser other questions tagged

You are not signed in. Login or sign up in order to post.