upload image to server ,image is from ,then i want to post image to server through ajax, server side using python flask framework, it needs base64 encoding format ,the question is how can i use javascript to convert image to base64 format.
$('.img-upload-btn').click(function(event) {
$("#img-upload").click();
});
$('#img-upload').on('change', function(event) {
event.preventDefault();
var img = $("#img-upload")[0].files[0];
console.log(toDataUrl(img.name));
var img_data = {
"spec_id": 212,
"file": img
};
console.log(img);
$.ajax({
url: 'http://10.0.0.75:5000/api/check_specification',
type: 'POST',
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function(data) {
alert(data);
},
failure:function(errorMsg) {
alert(errorMsg);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="btn-search full-width img-upload-btn">upload-img</button>
<input type="file" id="img-upload" >
Something like this you can get image in base64.
fileChange(e) {
/* any way to get the object input */
var file = document.querySelector('input[type=file]');
let reader = new FileReader();
if(file.files[0]) {
reader.onload = () => {
imgBase64 = reader.result;
console.log(reader.result);
//your request
}
reader.readAsDataURL(file[0]);
}
}
Related
I try to create upload photos in my nodejs site.
I used this code to choose file and upload the image:
var fileData = null;
function loadFile() {
var preview = document.querySelector('file');
var file = document.querySelector('input[type=file]').files[0];
var reader = new FileReader();
reader.onloadend = function () {
fileData = file;
}
if (file) {
reader.readAsDataURL(file);
}
}
function uploadFile() {
data = new FormData();
data.append('file', fileData);
$.ajax({
url: "/post_pdf/",
type: "POST",
data: data,
enctype: 'multipart/form-data',
processData: false,
contentType: false,
success: function(data) {
document.getElementById("result").innerHTML = 'Result: Upload successful';
},
error: function(e) {
document.getElementById("result").innerHTML = 'Result: Error occurred: ' + e.message;
}
});
}
With loadfile funcion i choose my image, and with Uploadfile function i upload the image with ajax.
if i use it alone its work perfect and upload the image to the location.
but when i try to add this code to my code, it make alot of errors.
in my code i send to back end all the forms in the pug file:
$('#account-form').ajaxForm({
error : function(e){
if (e.responseText == 'title-empty'){
av.showInvalidTitle();
}
},
success : function(responseText, status, xhr, $form){
if (status == 'success')
{
$('.modal-alert').modal('show');
console.log(responseText)
}}
});
i try to merge the ajaxform with the ajax but when i merege the formdata or i send in ajaxform the data of the file is send error.
how can i merge the codes?
thanks for helping.
Try to submit form it will submit form with your image.
let form = $("#form_id");
$.ajax({
url : $(form).attr("action"),
type: "POST",
dataType: "json",
processData: false,
contentType: false,
cache: false,
data: new FormData(form[0]),
success:function(data){
},
error: function (xhr, status, e) {
}
});
#Yogesh Patel
when i use this code:
$('#account-form-btn2').on('click', function(e) {
let form = $("#account-form");
$.ajax({
url: $(form).attr("action"),
type: "POST",
dataType: "json",
processData: false,
contentType: false,
cache: false,
data: new FormData(form[0]),
error: function (e) {
if (e.responseText == 'title-empty') {
av.showInvalidTitle();
}
},
success: function (responseText, status, xhr, $form) {
if (status == 'success') {
$('.modal-alert').modal('show');
}
}
});
});
for some reason it sends the values to "routes" three times.
and it doesn't catch the erorrs or success.
and it sends me to a white window with the value of the callback.
if needed, i can send the function that gets the values and returns them (app.post).
I was trying to upload file to a remote server using REST api by ajax/jquery with the following script, but it returns 400 error with a Bad request. I have tested the end point with curl, which is giving correct response and file is being uploaded.
$(document).ready(function () {
$("#btnSubmit").click(function (event) {
//stop submit the form, we will post it manually.
event.preventDefault();
fire_ajax_submit();
});
});
function fire_ajax_submit() {
// Get form
var form = $('#fileUploadForm')[0];
alert(form.files[0]);
var data = new FormData(form);
data.append("CustomField", "This is some extra data, testing");
$("#btnSubmit").prop("disabled", true);
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: "http://10.13.20.166:5332/fileUploadtoFolder",
data: data,
processData: false,
contentType: false,
cache: false,
timeout: 600000,
success: function (data) {
$("#result").text(data);
console.log("SUCCESS : ", data);
$("#btnSubmit").prop("disabled", false);
},
error: function (e) {
$("#result").text(e.responseText);
console.log("ERROR : ", e);
$("#btnSubmit").prop("disabled", false);
}
});
}
Change your code 👇
var data = new FormData(form);
Use this code 👇
// Create an FormData object
var data = new FormData(document.getElementById("fileUploadForm"));
Try again
I am trying to upload image through ajax. at theclient side i am using this code.
$(document).on('change','.image_upload',function(){
readURL(this);
});
///
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
save_profile_image(e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
else {
swal("Sorry - you're browser doesn't support the FileReader API");
}
}
function save_profile_image(image_data){
var image_code = encodeURIComponent(image_data);
$.ajax({
type: "POST",
url: '<?=base_url()."Dashboard/new_valet_picture";?>',
data:'valet_image='+image_code,
success: function(data){
alert('data');
}
});
}
while at the client side i am using codeigniter to save this as image. Image file is created but it won't display because it contains errors.Here is my CI function where this ajax request is being sent.
public function new_valet_picture(){
$user = $this->session->user_id;
$image_data = $this->input->post('valet_image');
$name= "valet_".$user.time().".png";
$profile_image = str_replace('data:image/png;base64,', '', $image_data);
$profile_image = str_replace(' ', '+',$profile_image);
$unencodedData=base64_decode($profile_image);
$pth = './uploads/valet_images/'.$name;
file_put_contents($pth, $unencodedData);
echo $name;
}
can anybody figure out where i am wrong.
you just wrong to pass parameter in ajax request :
this is your code
$.ajax({
type: "POST",
url: '<?=base_url()."Dashboard/new_valet_picture";?>',
data:'valet_image='+image_code,
success: function(data){
alert('data');
}
});
data:'valet_image='+image_code, is wrong pass and change that to data : {vallet_image : image_code}.
just changing the position of encodeURIComponent() helped me
///
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
save_profile_image(encodeURIComponent(e.target.result));
}
reader.readAsDataURL(input.files[0]);
}
else {
swal("Sorry - you're browser doesn't support the FileReader API");
}
}
function save_profile_image(image_data){
var image_code = image_data;
$.ajax({
type: "POST",
url: '<?=base_url()."Dashboard/new_valet_picture";?>',
data:'valet_image='+image_code,
success: function(data){
alert('data');
}
});
}
$.ajax({
type: 'GET',
dataType: 'image/jpeg',
url: '/Home/GetImage/' + img ,
success: function (data) {
i = new Image();
i.src = data;
$('#imageresult').append(i);
},
error: function () {
alert('error');
},
});
[HttpGet]
public ActionResult GetImage(string img)
{
string imageFile = System.Web.HttpContext.Current.Server.MapPath("~/Profile/Small/" );
var path = Path.Combine(imageFile, img );
var srcImage = Image.FromFile(path);
var stream = new MemoryStream();
srcImage.Save(stream, ImageFormat.Jpeg);
return File(stream.ToArray(), "image/jpeg");
}
It always falls into error function. If i remove dataType, then it doesn't fall into error function but it just shows long strings in the view. Why doesn't that work and show image in view?
You can do something Like this:
public ActionResult GetImage(string img)
{
string imageFile = System.Web.HttpContext.Current.Server.MapPath("~/Profile/Small/" );
var path = Path.Combine(imageFile, img );
var srcImage = Image.FromFile(path);
var stream = new MemoryStream();
srcImage.Save(stream, ImageFormat.Jpeg);
return Json(Convert.ToBase64String(stream.ToArray()), JsonRequestBehavior.AllowGet);
}
and the Ajax call:
$.ajax({
type: 'GET',
url: '#Url.Action("GetImage", "Home")',
success: function (data) {
$("#ItemPreview").attr('src', 'data:image/png;base64,' + data);
},
error: function () {
alert('error');
},
});
and the view:
<img id="ItemPreview" src="" />
of course you can append img dynamically, then bind its source after.
You are confusing the URL of an image with its actual content (the graphic bytes).
The /GetImage call returns the bytes, but you can never put data bytes in the i.src attribute because that attribute needs to be fed a URL.
It might work if you forget about the Ajax call and just use i.src = '/Home/GetImage/' + img;.
I am getting this following error. i am trying to upload the file to the server.can somebody please suggest something
Error - Failed to load resources: The server responded with a status of 405 method not allowed
</article>
<script>
function sendFileToServer(formData,status)
{
var uploadURL ="http://localhost/upfile/file/"; //Upload URL
var extraData ={}; //Extra Data.
var jqXHR=$.ajax({
xhr: function() {
var xhrobj = $.ajaxSettings.xhr();
if (xhrobj.upload) {
xhrobj.upload.addEventListener('progress', function(event) {
var percent = 0;
var position = event.loaded || event.position;
var total = event.total;
if (event.lengthComputable) {
percent = Math.ceil(position / total * 100);
}
//Set progress
status.setProgress(percent);
}, false);
}
return xhrobj;
},
url: uploadURL,
type: "POST",
contentType:false,
processData: false,
cache: false,
data: formData,
success: function(data){
status.setProgress(100);
$("#status1").append("File upload Done<br>");
}
});
status.setAbort(jqXHR);
}
contentType: 'multipart/form-data',
processData: false,
type: 'POST'
make sure you check your contentType