<Input Type="File"> Limit Selectable Files by Extensions

<input type=file> limit selectable files by extensions

Honestly, the best way to limit files is on the server side. People can spoof file type on the client so taking in the full file name at server transfer time, parsing out the file type, and then returning a message is usually the best bet.

Limit file format when using <input type=file>?

Strictly speaking, the answer is no. A developer cannot prevent a user from uploading files of any type or extension using front-end validation (HTML/JavaScript).

But still, the accept attribute of <input type = "file"> can help to provide a filter in the file select dialog box provided by the user's browser/OS. For example,

<!-- (IE 10+, Edge (EdgeHTML), Edge (Chromium), Chrome, Firefox 42+) --> 
<input type="file" accept=".xls,.xlsx" />

How to allow <input type=file> to accept only image files?

Use the accept attribute of the input tag. To accept only PNG's, JPEG's and GIF's you can use the following code:

<label>Your Image File
<input type="file" name="myImage" accept="image/png, image/gif, image/jpeg" />
</label>

How to filter input type=file dialog by specific file type?

See http://www.w3schools.com/tags/att_input_accept.asp:

The accept attribute is supported in all major browsers, except
Internet Explorer and Safari. Definition and Usage

The accept attribute specifies the types of files that the server
accepts (that can be submitted through a file upload).

Note: The accept attribute can only be used with <input type="file">.

Tip: Do not use this attribute as a validation tool. File uploads
should be validated on the server.

Syntax <input accept="audio/*|video/*|image/*|MIME_type" />

Tip: To specify more than one value, separate the values with a comma
(e.g. <input accept="audio/*,video/*,image/*" />.

restrict file upload selection to specific types

There is an html attribute for this specific purpose called accept but it has little support across browsers. Because of this server side validation is recommended instead.

<input type="file" name="pic" id="pic" accept="image/gif, image/jpeg" />

If you don't have access to the backend have a look at a flash based solution like SWFUpload.

See more on this here: File input 'accept' attribute - is it useful?

Angular File Upload

Here is a working example for file upload to api:

Step 1: HTML Template (file-upload.component.html)

Define simple input tag of type file. Add a function to (change)-event for handling choosing files.

<div class="form-group">
<label for="file">Choose File</label>
<input type="file"
id="file"
(change)="handleFileInput($event.target.files)">
</div>

Step 2: Upload Handling in TypeScript (file-upload.component.ts)

Define a default variable for selected file.

fileToUpload: File | null = null;

Create function which you use in (change)-event of your file input tag:

handleFileInput(files: FileList) {
this.fileToUpload = files.item(0);
}

If you want to handle multifile selection, than you can iterate through this files array.

Now create file upload function by calling you file-upload.service:

uploadFileToActivity() {
this.fileUploadService.postFile(this.fileToUpload).subscribe(data => {
// do something, if upload success
}, error => {
console.log(error);
});
}

Step 3: File-Upload Service (file-upload.service.ts)

By uploading a file via POST-method you should use FormData, because so you can add file to http request.

postFile(fileToUpload: File): Observable<boolean> {
const endpoint = 'your-destination-url';
const formData: FormData = new FormData();
formData.append('fileKey', fileToUpload, fileToUpload.name);
return this.httpClient
.post(endpoint, formData, { headers: yourHeadersConfig })
.map(() => { return true; })
.catch((e) => this.handleError(e));
}

So, This is very simple working example, which I use everyday in my work.

Only accept a certain file type in FileField, server-side

One very easy way is to use a custom validator.

In your app's validators.py:

def validate_file_extension(value):
import os
from django.core.exceptions import ValidationError
ext = os.path.splitext(value.name)[1] # [0] returns path+filename
valid_extensions = ['.pdf', '.doc', '.docx', '.jpg', '.png', '.xlsx', '.xls']
if not ext.lower() in valid_extensions:
raise ValidationError('Unsupported file extension.')

Then in your models.py:

from .validators import validate_file_extension

... and use the validator for your form field:

class Document(models.Model):
file = models.FileField(upload_to="documents/%Y/%m/%d", validators=[validate_file_extension])

See also: How to limit file types on file uploads for ModelForms with FileFields?.

Warning

For securing your code execution environment from malicious media files

  1. Use Exif libraries to properly validate the media files.
  2. Separate your media files from your application code
    execution environment
  3. If possible use solutions like S3, GCS, Minio or
    anything similar
  4. When loading media files on client side, use client native methods (for example if you are loading the media files non securely in a
    browser, it may cause execution of "crafted" JavaScript code)

Bootstrap File Input - limit file types

While this certainly works, the browse should only allow the chosen
types to be selected. What additional parameter(s) and/or other
changes are needed so that the browse window limits the selection to
the chosen types?

Try setting accepted types of file extension for input type="file" element using accept attribute , with value being file extensions separated by comma . Only file extnsion types defined as value of accept attribute should be displayed at "Open File" dialog

<input type="file" accept=".jpg,.gif,.png" />


Related Topics



Leave a reply



Submit