This article shows how to get an image from the Model and send the image as a base64 string using jQuery.
This article is helpful for beginners who are working with partial views and jQuery.
Using the code
- HTML code for file upload.
- Partial view tag, how do render with HTML, is coded below. "
the partial view name.
- Get the image from the model as a base64 string.
It is data.
lstCompanyInfo.UploadFileName is a list object.
data.lstCompanyInfo.UploadFileName is a property. Dynamically add the base64 string to:
var imag = "<img " + "src='" + "data:image/jpg;base64," +
data.lstCompanyInfo.UploadFileName + "' style='width:100px'/>";
Save the image from upload file to path to base64 string
- In the fileupload control
OnChange function we convert the image from the path.
FileList is used to list files. We can also add multiple files at
the same time. But here we are using a single file.
fileList; is used for the first location.
Filereader is used to read the file
var fileList = this.files;
var file = fileList;
var r = new FileReader();
var binimage = r.result;
The reader result is assigned the base64 string
data:image/jpeg;base64 that contains the JPEG extension string. But it does not accept it and we have to replace
the string with an empty one or else you can replace the string with
data:image/jpg;base64 and it will work fine.
binimage1 = binimage.replace('data:image/jpeg;base64,', '');
This is my very first for article writing. If there any mistakes, let me know. Thank you very much.