Principales respuestas
Enviar una imagen por ajax y recibirlo como parametro en Web Service utilizando C#

Pregunta
-
Hola estoy tratando de enviar una imagen ya convertida en Base64 por ajax, y quiero recibirlo como parametro en el lado del Web Service pero no me lo recibe lo estoy realizando de la siguiente manera.
En el html tengo lo siguiente:
<input type="file" id="fileLoader" name="files" onchange="loadImageFileAsURL()" /> <p id="ImagenBase64"></p>
en el evento "onchange" de "file" me lo convierte en Base64 a travez desde este Js.
en el parrafo me muestra la imagen ya convertida a Base64 el cual me servira para enviarle al webservice.
function loadImageFileAsURL() { var filesSelected = document.getElementById("fileLoader").files; if (filesSelected.length > 0) { var fileToLoad = filesSelected[0]; var fileReader = new FileReader(); fileReader.onload = function (fileLoadedEvent) { var ImagenBase64= document.getElementById("ImagenBase64"); ImagenBase64.innerText = fileLoadedEvent.target.result; }; fileReader.readAsDataURL(fileToLoad); }
y en esta función igual Js lo quiero enviar a travez de Ajax.
var Im = $('#ImagenBase64').text() var Imagen = Im.replace('data:image/jpeg;base64,', '') $.ajax({ type: "POST", url: "Servicios/RecibirImagen.asmx/RecibirIm", data: "{'Imagen':'" + Imagen + "'}", contentType: 'application/json; charset=UTF-8', dataType: "json", success: function (response) { if (response.d == 'Recibido') { alert('Recibido con exito') } }, });
En el Web service lo tengo de esta forma.
[WebMethod] public string RecibirIm(string Imagen) { string msg = ""; string Im = Imagen; if (Im != null) { msg = "Recibido"; } return msg; }
pero no recibe el parametro que le envío desde Ajax que estaré haciendo mal, les agradeceria.
Gracias
Respuestas
-
Hola Balopezm,
Porque no agregas el error en el $.Ajax para que muestre si existe algún problema.
Has verificado en tu explorador, en la parte de consola si tienes algún problema de redacción el en JS.
Prueba haciendo estos cambios :
$.ajax({ type: "POST", url: "Servicios/RecibirImagen.asmx/RecibirIm", data: {'Imagen': + Imagen }, contentType: 'application/json; charset=UTF-8', dataType: "json", success: function (response) { if (response.d == 'Recibido') { alert('Recibido con exito') } }, error: function (request, status, error) { alert(request.responseText); } });
Saludos.
JC NaupaCrispín
Lima - Perú
La magia no existe, la programación SI
Todas las respuestas
-
hola
Si inspeccionas el html de la pagina puedes ver que en ImagenBase64 esta la imagen asignada?
Estas seguro que con
var Im =$('#ImagenBase64').text()
tomas el string de la imagen, no sera $('#ImagenBase64').html()
----
Ademas tienes que definir el webmethod como static
public static string RecibirIm(string Imagen)
saludos
Leandro Tuttini
Blog
MVP Profile
Buenos Aires
Argentina -
-
Hola Balopezm,
Porque no agregas el error en el $.Ajax para que muestre si existe algún problema.
Has verificado en tu explorador, en la parte de consola si tienes algún problema de redacción el en JS.
Prueba haciendo estos cambios :
$.ajax({ type: "POST", url: "Servicios/RecibirImagen.asmx/RecibirIm", data: {'Imagen': + Imagen }, contentType: 'application/json; charset=UTF-8', dataType: "json", success: function (response) { if (response.d == 'Recibido') { alert('Recibido con exito') } }, error: function (request, status, error) { alert(request.responseText); } });
Saludos.
JC NaupaCrispín
Lima - Perú
La magia no existe, la programación SI -
Gracias por responder, verificando en este momento si me aparece un error
"Error durante la serializacion o deserializacion mediante JavaScriptSerializer de Json, la longitud de la cadena
supera el valor establecido en la propiedad maxJsonLenght del parametro input" -
-
Amigo tengo este codigo y no se cm implementarlo :/
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta charset="utf-8">
<title>Subir imagen blob</title>
</head>
<body>
<%
%>
<form id="alta-heroe" name="alta-heroe" data-insertar action="">
<table border="0" align="center">
<tr>
<td>Nombre de objeto :</td>
<td><input type="text" id="Blob_Person_ID" name="Blob_Person_ID" size="40" required></td>
</tr>
<tr>
<td>Archivo :</td>
<td><input id="Blob_Segment" name="Blob_Segment" type="file" size="40" required></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" id="submitForm" value="Enviar"></td>
</tr>
</table>
<%
%>
<script src="https://code.jquery.com/jquery-3.1.1.min.js" integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=" crossorigin="anonymous"></script>
<script>
var error = false;
$(function() {
$('#submitForm').click(function() {
error=false;
if(!$('#Blob_Segment')[0].files || !$('#Blob_Segment')[0].files[0]) {
error = true;
alert("Debe seleccionar una imagen"); //No file selected exception
}
if(!$('#Blob_Person_ID').val() || $('#Blob_Person_ID').val() == "") {
error = true;
alert("Debe ingresar un nombre"); //Empty field exception
}
error=false;
if(!error) {
console.log(ajax);
var FR= new FileReader();
FR.addEventListener("load", function(e) {
var imageB64 = e.target.result.split(',');
var contentType = imageB64[0].split(':')[1].split(';')[0];
console.log(imageB64[1].substring(0,10));
$.ajax({
console.log(imageB64[1].substring(0,50));
type: "post",
//dataType: "html".,
url: "updatefoto.asp",
data: {
Blob_Segment: imageB64[1], //convierte la imagen a bits Leave this first as it is being parsed by Back-end ASP
Blob_Person_ID: $('#Blob_Person_ID').val(),
}
/*contentType: "text/plain; charset:UTF-8",*/
/* contentType: "text/plain";*/
/* dataType: "text",*/
/*cache: false,*/
/* async: false,*/
/* success: function(r) {
console.log(r);
}*/
});
});
FR.readAsDataURL($('#Blob_Segment')[0].files[0]);/*aqui es donde me manda error :/ :/ :/ : /: :/ ya no se q poner :/*/
}
});
});
</script>-->
</form>
</body>
<script src="https://code.jquery.com/jquery-3.1.1.min.js" integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=" crossorigin="anonymous"></script>
<script type="text/javascript" src="formulario.js"></script>
</html>
-
amigo tengo un codigo acerca de subir una imagen a un campo blob tengo un codigo pero no se q me falte para llevarlo acabo podrias ayudarme?? :/
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta charset="utf-8">
<title>Subir imagen blob</title>
</head>
<body>
<%
%>
<form id="alta-heroe" name="alta-heroe" data-insertar action="">
<table border="0" align="center">
<tr>
<td>Nombre de objeto :</td>
<td><input type="text" id="Blob_Person_ID" name="Blob_Person_ID" size="40" required></td>
</tr>
<tr>
<td>Archivo :</td>
<td><input id="Blob_Segment" name="Blob_Segment" type="file" size="40" required></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" id="submitForm" value="Enviar"></td>
</tr>
</table>
<%
%>
<script src="https://code.jquery.com/jquery-3.1.1.min.js" integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=" crossorigin="anonymous"></script>
<script>
var error = false;
$(function() {
$('#submitForm').click(function() {
error=false;
if(!$('#Blob_Segment')[0].files || !$('#Blob_Segment')[0].files[0]) {
error = true;
alert("Debe seleccionar una imagen"); //No file selected exception
}
if(!$('#Blob_Person_ID').val() || $('#Blob_Person_ID').val() == "") {
error = true;
alert("Debe ingresar un nombre"); //Empty field exception
}
error=false;
if(!error) {
console.log(ajax);
var FR= new FileReader();
FR.addEventListener("load", function(e) {
var imageB64 = e.target.result.split(',');
var contentType = imageB64[0].split(':')[1].split(';')[0];
console.log(imageB64[1].substring(0,10));
$.ajax({
console.log(imageB64[1].substring(0,50));
type: "post",
//dataType: "html".,
url: "updatefoto.asp",
data: {
Blob_Segment: imageB64[1], //convierte la imagen a bits Leave this first as it is being parsed by Back-end ASP
Blob_Person_ID: $('#Blob_Person_ID').val(),
}
/*contentType: "text/plain; charset:UTF-8",*/
/* contentType: "text/plain";*/
/* dataType: "text",*/
/*cache: false,*/
/* async: false,*/
/* success: function(r) {
console.log(r);
}*/
});
});
FR.readAsDataURL($('#Blob_Segment')[0].files[0]);/*aqui es donde me manda error :/ :/ :/ : /: :/ ya no se q poner :/*/
}
});
});
</script>-->
</form>
</body>
<script src="https://code.jquery.com/jquery-3.1.1.min.js" integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=" crossorigin="anonymous"></script>
<script type="text/javascript" src="formulario.js"></script>
</html>