Image preview before upload in IE and Chrome

前端 未结 7 2204
说谎
说谎 2021-02-14 19:51

I am trying to design a module in which I would like to show a preview of the image to the user before he uploads the image to database.

I have found a solution which wo

7条回答
  •  没有蜡笔的小新
    2021-02-14 20:34

    There is no cross platform way to accomplish this using only HTML/JavaScript. It is possible, however, using a very basic programmatic approach:

    Step 1: Binding to Blur
    Bind a "blur" event to your file input field, like so:

    $("#input_field").blur(function(event){
        alert("Blur!");
    });
    

    Step 2: Server-Side Thumbnailing
    You're going to have to write a small application/route on your server side application that simply accepts a form that contains in input file, and generates a temporary output file. You could even just temporarily store the filedata in your database, rather than write individual files to disk; the implementation is up to you. When this route receives a request, it should thumbnail the image, and then return a path to that thumbnail

    Step 3: AJAX
    First, choose one of the many available jQuery "AJAX Upload" libraries to make the form that contains your file upload it via AJAX. Apply that library to the form(For the examples below, I'll use ajaxForm.), and then modify your blur:

    // AJAX the form
    $("#your_form").ajaxForm({
        success: function(response){
            // Insert your returned thumbnail into your DOM.
        }
    });
    
    // Modify the blur
    $("#input_field").blur(function(event){
        $("#input_field").closest("form").submit();
    });
    

    Issues:
    There will be issues with the approach above. Making your form AJAX will mean submitting it regularly will break - not to mention that the thumbnail route will be different than the actual form submission route. Use some workarounds (for example, have a secondary hidden form, and the blur event copies the file-upload onto it, and then submits it).

提交回复
热议问题