My english is not good, but I will try to explain the problem. I'm trying to load multiple images in an asp.net webforms application, but when I'm loading the files the first image doesn't load. Look at the following code:
$('#loadImg').change(function () {
for (var i = 0; i <= this.files.length; i++) {
if (this && this.files[i]) {
var reader = new FileReader(), valor;
reader.readAsDataURL(this.files[i]);
reader.onload = function () {
valor = reader.result
};
var obj = new Object();
obj.Objn = i;
obj.Name = this.files[i].name;
obj.Tipo = this.files[i].type;
obj.Peso = this.files[i].size;
obj.Obji = valor;
var params = JSON.stringify(obj);
if (IsValid(obj.Tipo)) {
$.ajax({
type: "POST",
url: uri1,
data: params,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
if (data.d) {
$('#objimg').attr('src', obj.Obji);
}
},
async: false,
error: function (XMLHttpRequest) {
alert("Error al cargar la imagen");
}
});
}
}
}
function IsValid(iTipo) {
switch (iTipo) {
case 'image/png': case 'image/gif': case 'image/jpeg': case 'image/pjpeg':
return true; break;
default:
return false;
}
}
Related
I'm trying to send an ajax form to a controller, but the data attribute arrive empty to the controller, this is my code:
var fd = new FormData();
fd.append('asd', 123);
console.log(fd);
var idServicio = $("#id-building-form-add-new-stand").val();
var idEdificio = $("#id-service-form-add-new-stand").val();
var piso = $("#id-floor-form-add-new-stand").val();
var idJornada = $("#id-jornada-form-add-new-stand").val();
fd.append("idServicio", idServicio);
fd.append("idEdificio", idEdificio);
fd.append("piso", piso);
fd.append("idJornada", idJornada);
fd.append("jsonStand", JSON.stringify(jsonStand));
fd.append("accion", "1");
console.log(fd);
after I put my ajax code:
$.ajax({
method: "POST",
mimeType: "multipart/form-data",
url: epStand,
processData: false,
contentType: false,
data: fd,
success: function (statusM) {
//toggleModalCargando();
var data = JSON.parse(statusM);
if (data.status === 1) {
console.log("éxito");
$.unblockUI();
} else {
if (data.status === 0) {
$.unblockUI();
throwAlert(data.dataObject[0].message, "error");
} else {
$.unblockUI();
throwAlert(data.descripcion, "error");
}
}
}
});
However the fd variable is empty in all my logs console and of course in the controller.
Facing error on JSON.stringify(ApplObj) :
How to post this object to controller
JQuery Code -
var ApplName = $("#ApplicantName").val();
var ApplMobile = $("#ApplicantMobile").val();
var ApplEmail = $("#ApplicantEmailId").val();
var ApplFHName = $("#ApplicantFHName").val();
var ApplObj = {
ApplicantName: ApplName, ApplicantMobile: ApplMobile, ApplicantEmailId: ApplEmail, ApplFHName: ApplicantFHName
}
$.ajax({
url: '#Url.Action("SaveApplicatDetail", "Dashboard")',
data: JSON.stringify(ApplObj),
dataType: 'json',
type: 'POST',
contentType: "application/json; charset=utf-8",
success: function (data) {
alert(data);
}
});
Controller Code...
this jsonresult used for save records and return value...
this code is working in other project....
public JsonResult SaveApplicatDetail()
{
try
{
var resolveRequest = HttpContext.Request;
TicketMasterModel TMM = new TicketMasterModel();
resolveRequest.InputStream.Seek(0, SeekOrigin.Begin);
string jsonString = new StreamReader(resolveRequest.InputStream).ReadToEnd();
if (jsonString != null)
{
TMM = (TicketMasterModel)js.Deserialize(jsonString, typeof(TicketMasterModel));
}
int TicketId = 0;
using (var db = new UnitOfWork())
{
DAL.tbl_TrnTicketMaster TM = new DAL.tbl_TrnTicketMaster();
TM.ApplicantName = TMM.ApplicantName;
TM.ApplicantMobile = TMM.ApplicantMobile;
TM.ApplicantEmailId = TMM.ApplicantEmailId;
TM.ApplicantFHName = TMM.ApplicantFHName;
TM.FK_CompanyId = 1;
TM.CustomerId = UserSession.UserId;
TM.IsSubmissionLocked = false;
TM.CreatedBy = UserSession.UserId;
db.tbl_TrnTicketMaster.Insert(TM);
TicketId = TM.PK_TicketId;
}
return Json(TicketId, JsonRequestBehavior.AllowGet);
}
catch (Exception)
{
throw;
}
}
basically JSON.stringify turns a Javascript object into JSON text and stores that JSON text in a string.
try this,
var ApplName = $("#ApplicantName").val();
var ApplMobile = $("#ApplicantMobile").val();
var ApplEmail = $("#ApplicantEmailId").val();
var ApplFHName = $("#ApplicantFHName").val();
var ApplObj = {
'ApplicantName': ApplName, 'ApplicantMobile': ApplMobile, 'ApplicantEmailId': ApplEmail, 'ApplFHName': ApplicantFHName
}
$.ajax({
url: '#Url.Action("SaveApplicatDetail", "Dashboard")',
data: JSON.stringify(ApplObj),
dataType: 'json',
type: 'POST',
contentType: "application/json; charset=utf-8",
success: function (data) {
alert(data);
}
});
Problem Resolved -
"JSON.stringify" is used array to convert it.
var ApplName = $("#ApplicantName").val();
var ApplMobile = $("#ApplicantMobile").val();
var ApplEmail = $("#ApplicantEmailId").val();
var ApplFHName = $("#ApplicantFHName").val();
var ApplDetails = {
ApplicantName: ApplName,
ApplicantMobile: ApplMobile,
ApplicantEmailId: ApplEmail,
ApplicantFHName: ApplFHName
}
var ApplObj = { ApplicantDetail: ApplDetails };
$.ajax({
url: '#Url.Action("SaveApplicatDetail", "Dashboard")',
data: JSON.stringify(ApplDetails),
dataType: 'json',
type: 'POST',
contentType: "application/json; charset=utf-8",
success: function (data) {
}
});
This question already has answers here:
How to append whole set of model to formdata and obtain it in MVC
(4 answers)
Closed 7 years ago.
I need post a uploades file and model, i use mvc this the code in the view:
function GuardarDocumento() {
var fileUpload;
var tipoDoc;
if (currentTabTitle == "#tab-AT") {
fileUpload = $("#inputFileAT").get(0);
tipoDoc = 'A';
}
var files = fileUpload.files;
var data = new FormData();
for (var i = 0; i < files.length; i++) {
data.append(files[i].name, files[i]);
}
var documento = {
Id_emd: 0,
Id_emm: {
Id_emm: id,
Tipo: tipo,
},
Tipo_emd: tipoDoc,
Fecha_emd: $("#txtFechaDocAT").val(),
Nombre_emd: $("#txtNombreDocAT").val(),
}
$.ajax({
url: "/Empleado/GuardarDocumento/" + JSON.stringify(documento),
type: "POST",
data: data,
contentType: false,
processData: false,
success: function (data) {
if (data.success) {
alert("Documento Guardado con Éxito.");
Cancelar();
}
else {
alert(data.message);
}
},
error: function (xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
}
And the controller code:
[HttpPost]
public ActionResult GuardarDocumento(clsDocumentoEmpleadoModel documento)
{
try
{
if (Request.Files.Count > 0)
{
clsEmpleadoBLL bll = new clsEmpleadoBLL();
bll.PostedFile = Request.Files[0];
documento.Archivo_emd = Request.Files[0].FileName;
bll.AddDocument(documento);
}
else
{
return Json(new { success = false, message = "No ha seleccionado ningún archivo." });
}
}
catch (Exception ex)
{
GENException.Write(ex, "EmpleadoController.GuardarDocumento");
return Json(new { success = false, message = string.Format("Error: {0}", ex.Message) });
}
return Json(new { success = true, message = "Documento Guardado Correctamente." });
}
It does not work, bad request. If I put url: "/Empleado/GuardarDocumento/" + documento, i get into controller code but model is null.
What is wrong? I am trying send to controller both uploaded file and model, how can I do that?
The type that you're sending to the controller action must match the type the action is expecting. You're sending a FormData, and you're expecting a clsDocumentoEmpleadoModel.
getMediaBinary: function() {
var file = document.getElementById('photo').files[0],
reader = new FileReader(),
deferred = $.Deferred();
reader.onloadend = function () {
return deferred.resolve(reader.result);
};
reader.readAsBinaryString(file);
return deferred.promise();
},
getMediaData: function() {
var file = document.getElementById('photo').files[0],
reader = new FileReader(),
deferred = $.Deferred();
reader.onloadend = function () {
return deferred.resolve(reader.result);
};
reader.readAsDataURL(file);
return deferred.promise();
},
uploadMedia: function() {
var formData = new FormData();
$.when(JTWEET.getMediaBinary(), JTWEET.getMediaData() ).then(function(media, media_data) {
formData.append('media', media);
formData.append('media_data', media_data);
return $.ajax({
url: JTWEET.routerUrl + 'https://upload.twitter.com/1.1/media/upload.json',
type: 'POST',
// data: { media: document.getElementById('photo').files[0].name, media_data: JTWEET.getMediaData() },
data: formData,
contentType: false,
processData: false,
success: function() {
console.dir(arguments);
},
error: function() {
console.dir(arguments);
}
});
});
},
I'm getting the next error:
{"errors":[{"code":38,"message":"media parameter is missing."}]}
What am I missing ?
Try checking this one out - https://twittercommunity.com/t/post-media-upload-json-always-returns-media-parameter-is-missing/27962
Figured it out finally. Two things are important here:
1. the parameter name has to be “media”, not “media[]”
2. Do not set the contentType property. It prevents a Content-Type header with the correct boundary value from being automatically created.
A correct options object looks like this:
var options = {
"oAuthServiceName":"twitter",
"oAuthUseToken":"always",
method: "POST",
payload: { "media" : imageblob }
};
I want to find a way,give a dom as parameter and get data, from image_preview.
and separate image_preview.model() and image_preivew.on_chage() is event handler
make image_preview reusable not hardcode inside
I espect I will call image_preview pass dom in parameter, and return src as response , then I can use repsponse do something like append ...
var image_preview = {
on_change: function(wrap_dom, input_dom) {
$(wrap_dom).on('change', input_dom, function(event) { // I have to use on change because there are possible the `input dom` is new append...
var el_obj = $(this)[0];
var form_data = new FormData();
var file_length = el_obj.files.length;
for (var i = 0; i < file_length; i++) {
form_data.append("file[]", el_obj.files[i]);
}
image_preview.model(form_data).done(function(response) {
// console.log(response); // this is work
return response;
});
});
},
model: function(form_data) {
return $.ajax({
url: uri_public+'/admin/ajax/preview_file',
type: 'POST',
data: form_data,
processData: false,
contentType: false,
// async: false
});
}
}
var app_thumbnail = {
preview_controller: function() {
var wrap_dom = '.thumbnail';
var input_dom = '.upload-form input';
var result = image_preview.on_change(wrap_dom, input_dom);
// pass result to render view like append dom....
},
render: function() {
},
}
app_thumbnail.preview_controller();
Here is the easiest thing you can do:
var image_preview = {
on_change: function(wrap_dom, input_dom) {
$(wrap_dom).on('change', input_dom, function(event) {
var el_obj = $(this)[0];
var form_data = new FormData();
var file_length = el_obj.files.length;
for (var i = 0; i < file_length; i++) {
form_data.append("file[]", el_obj.files[i]);
}
image_preview.model(form_data).done(function(response) {
app_thumbnail.preview_controller(response);
});
});
},
model: function(form_data) {
return $.ajax({
url: uri_public+'/admin/ajax/preview_file',
type: 'POST',
data: form_data,
processData: false,
contentType: false,
// async: false
});
}
}
var app_thumbnail = {
preview_controller: function(response) {
var wrap_dom = '.thumbnail';
var input_dom = '.upload-form input';
var result = response;
}
}
// If you want to initialize it.
// image_preview.on_change(..., ...);