bootstrap fileinput control + django background upload, echo simple use

Keywords: Javascript JSON github JQuery Django

1. Control Download:

Official website:

Files to be imported: 1. jquery.js

          2,bootstrap.js  bootstrap.css

3. The font awesome.css control icon uses font awesome, so it needs to be imported

          4,finleinput.js  fileinput.css

5. zh.js set Chinese, default English

2. Examples:

1. Set HTML: multiple to batch upload. Just set class to file loading. If it is set to class="file", Chinese will not take effect. The effect is as follows

<input id="upload-file" type="file" class="file-loading" name="attachment" multiple />


2: initialization: js code, otherwise use the default setting, refer to the official website for detailed api:


            var aryFiles = Array();
                language: 'zh',     // Set language, need to import locales/zh.js file
                uploadUrl: '/att_upload/',     // Upload path
                maxFileSize: 0,     // Upload file size limit, triggered msgSizeTooLarge Tips
                // {name}: Will be replaced by the uploaded file name,{size}: Will be replaced by the size of the uploaded file,{maxSize}: Will be maxFileSize Parameter substitution.
                msgSizeTooLarge: '"{name}" ({size} KB) Exceeded the maximum allowed upload size {maxSize} KB. Please upload again!',
                showPreview: true,  // Display Preview
                showUpload: true,   // Display upload button or not
                showCaption: true,  // Display text description or not
                showClose: false,   // Hide top right corner×
                uploadAsync: true, // Whether to upload asynchronously
                initialPreviewShowDelete: true, // Delete button in Preview
                autoReplace: true,  // When the maximum number of uploads is reached, the previous attachments will be replaced automatically
                uploadExtraData: function () {  // uploadExtraData Carry additional parameters when uploading csrftoken
                    return {csrfmiddlewaretoken: $.cookie('csrftoken'), doc_uuid: $('[name=doc_uuid]').val()}
                initialPreview :[],  // Default Preview settings, which are used in echo
                initialPreviewConfig: [],  // Detailed configuration of default preview, which will be used in echo
            }).on("fileuploaded", function (e,data,previewId,index) {
                // Events triggered after successful upload
            }).on("fileclear", function (e) {
                // Remove the event triggered by the button, and use the event to batch delete
$.ajax({ url: '/del_all_att/', method: 'post', dataType: 'json', data: {'aryFiles': JSON.stringify(aryFiles)}, success: function (data) {                } }) }).on("filepredelete", function (e, key, jqXHR, data) { // Delete button in preview to delete the event triggered by the uploaded file }).on("fileloaded", function (e, file, previewId) { // aryFile.length = 0; // Event triggered after loading preview, add all filenames to global variables aryFiles Array aryFiles.push(; })


setting code:

# Upload file path
MEDIA_URL = '/upload_files/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'upload_files')

url Code: corresponding to the uploadUrl parameter in fileinput


urlpatterns = [
    re_path(r'att_upload/', views.attachment_upload, name='att_upload'),  # upload
    re_path(r'del_doc_file/', views.del_doc_file, name='del_doc_file'),  # Single deletion
    re_path(r'del_all_att/', views.del_all_att, name='del_all_att'),  # Batch deletion
# Upload files url Route
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)


views Code:

def attachment_upload(request):
    att_file = request.FILES.get('attachment', None)
    doc_uuid = request.POST.get('doc_uuid', None)
    if att_file:
        # Save files to hard disk
        file_dir = os.path.join(os.path.join(os.path.dirname(os.path.dirname(__file__)), 'upload_files'),
        f = open(file_dir, 'wb')
        for i in att_file.chunks():
        # Download and Preview url
        url = settings.MEDIA_URL +
        file_type ='[^.]+\w$',  # Advanced file suffix

     # File type, can be added or deleted by yourself img_list
= ['jpg', 'jpeg', 'jpe', 'gif', 'png', 'pns', 'bmp', 'png', 'tif'] pdf_list = ['pdf'] text_list = ['txt', 'md', 'csv', 'nfo', 'ini', 'json', 'php', 'js', 'css'] # bootstrap fileinput Echo parameters of the uploaded file, initialPreview(List) initialPreviewConfig(List) initialPreview = []
     # Generate different HTML according to the uploaded file type,
if file_type in img_list: initialPreview.append("<img src='" + url + "' class='file-preview-image' style='max-width:100%;max-height:100%;'>") elif file_type in pdf_list: initialPreview.append("<div class='file-preview-frame'><div class='kv-file-content'><embed class='kv-preview-data file-preview-pdf' src='" + url + "' type='application/pdf' style='width:100%;height:160px;'></div></div>") elif file_type in text_list: initialPreview.append("<div class='file-preview-frame'><div class='kv-file-content'><textarea class='kv-preview-data file-preview-text' title='" + + "' readonly style='width:213px;height:160px;'></textarea></div></div>") else: initialPreview.append("<div class='file-preview-other'><span class='file-other-icon'><i class='glyphicon glyphicon-file'></i></span></div>") initialPreviewConfig = [{ 'caption':,  # File title 'type': file_type,  # file type 'downloadUrl': url,  # Download address 'url': '/del_doc_file/',  # url of delete button in Preview 'size': os.path.getsize(file_dir),  # file size 'extra': {'doc_uuid': doc_uuid}, # Delete parameters carried by files 'key':,  # Parameters carried by ajax when deleting }]
     # Return json data. initialPreview initialPreviewConfig will replace the two parameters append:True when initializing the plug-in to add content to the initialization preview return HttpResponse(json.dumps({'initialPreview':initialPreview, 'initialPreviewConfig':initialPreviewConfig,'append': True})) else: return HttpResponse(json.dumps({'status': False}))

Delete the code and do not upload it. You can write it according to your own needs. Note: get it from request.POST.get(), and the value of extra and key set by initialPreviewConfig in the attachment upload method.

There is no official method for batch deletion, so two events, fileloaded and fileclear, are used to complete the deletion. I hope you can let me know. Thank you very much..

If it's not well written, please understand. If there is any mistake or need to be corrected, please point out in time.

Posted by amjohnno on Mon, 02 Dec 2019 12:22:35 -0800