I am writing a flask server using Jinja2 template. In a form, I have a file field letting the user to upload an image.
When the form fails validation, the same form will be shown with a flash message. I want the form to be filled with old values, especially the image the user has uploaded. However, I can not figure out how to achieve this.
The object python sent to the Jinja2 template is something like
<FileStorage: 'launch-image-3.5@2x.png' ('image/png')>
I'm using a macro to render a file input as follows (I'm using Bootstrap 4):
{% macro file_uploader(file_name, url_name, title, url) %}
<fieldset class="form-group">
<strong>{{ title }}</strong>
<br/>
<label class="file">
<input type="file" class="form-control-file" id="{{ file_name }}" name="{{ file_name }}">
<span class="file-custom"></span>
</label>
<input type="text" class="form-control" id="{{ url_name }}" name="{{ url_name }}" placeholder="{{ title }} URL"
value="{{ url or '' }}">
<img id="{{ file_name }}-preview" class="img-thumbnail" src="{{ url or '' }}"
style="margin-top: 8px; max-width: 50%; display: none;">
</fieldset>
<script>
$("#{{ file_name }}").on("change", function () {
$("#{{ url_name }}").val("");
var input = this;
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
var preview = $("#{{ file_name }}-preview");
preview.attr("src", e.target.result);
preview.show();
};
reader.readAsDataURL(input.files[0]);
}
});
</script>
{% endmacro %}
As long as the user upload an image by clicking the input, a preview of the image will be show in the img tag.
My problem is, how to programmatically set an image to the file input, such that the img tag will be triggered to show the preview, and when the user click submit button, the same image will be again sent to the server within the form.
BTW, my form is a multipart/form-data one.