I've worked on this but couldn't fully figure out.
Basically, what I need is to upload 2 or more files separately (only on demand one by one, not all files at once) using Ajax upload. Currently, I have 2 file inputs but somehow, the JavaScript code always uploads the first file input (the one inside "formContentProperty").
Here is my HTML code:
<div>
<form enctype="multipart/form-data" id="formContentProperty">
<input id="fileContentProperty" type="file" name="fileContentProperty" />
<a id="uploadbuttonContentProperty" href="javascript:void(0)">
<span>Upload 1</span>
</a>
</form>
<progress></progress>
</div>
<div>
<form enctype="multipart/form-data" id="formContentPreviewImage">
<input id="fileContentPreviewImage" type="file" name="fileContentPreviewImage"/>
<a id="uploadbuttonContentPreviewImage" href="javascript:void(0)">
<span>Upload 2</span>
</a>
</form>
<progress></progress>
</div>
Here is my JavaScript code:
$('#uploadbuttonContentProperty').click(function () {
return UpdoadFile('formContentProperty', 'divUploadContentPropertyResultMessage');
});
$('#uploadbuttonContentPreviewImage').click(function () {
return UpdoadFile('formContentPreviewImage', 'divUploadContentPreviewImageResultMessage');
});
function UpdoadFile(formElementId, divMessageElementId) {
var formData = new FormData($('form')[0]);
$.ajax({
url : '<%= base.AjaxUploadHandlerPath %>', //Server script to process data
type : 'POST',
xhr : function() { // Custom XMLHttpRequest
var myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){ // Check if upload property exists
myXhr.upload.addEventListener('progress',progressHandlingFunction, false); // For handling the progress of the upload
}
return myXhr;
},
//beforeSend: beforeSendHandler,
success : function(response) {
var obj = $.parseJSON(response);
$('#' + divMessageElementId).html(obj.ResultMessage);
},
//error : errorHandler,
data : formData,
//Options to tell jQuery not to process data or worry about content-type.
cache : false,
contentType : false,
processData : false
});
};
function progressHandlingFunction(e){
if(e.lengthComputable)
$('progressContentProperty').attr({ value: e.loaded, max: e.total });
}
I'd really appreciate any help.
To upload files using ajax file upload
<script>
function uploadFiles()
{
var files = $('#previewFile')[0].files;
var totalFiles = files.length
for(var i=0; i < totalFiles; i++)
{
var formData = new FormData();
formData.append("previewFile",files[i]);
doAjaxFileUpload("/storeTempFile.do", formData,function(data)
{
data = eval(data);
if (data.result=="success")
{
alert("File uploaded successfully");
}
else
{
alert("Error occured : "+data);
}
},
function(data)
{
alert("Error occured : "+data);
});
}
}
function doAjaxFileUpload(actionURL,params,callbackSuccessFunction,callbackFailureFunction)
{
$.ajax(
{
url: actionURL,
type: "POST",
data: params,
processData: false,
contentType: false,
error: callbackFailureFunction,
success : callbackSuccessFunction
});
}
</script>
Related
The Excel sheet want to read while it upload on a button click in MVC5.The uploaded excel file name is passed into action using AJAX method.Here the file variable get null value in posted method.
Here how can pass selected file as HttpPostedFileBase in the below ajax method.
`
<input style="display:none" type="file" id="fileupload1" />
<button type="button" onclick='$("#fileupload1").click()'>UPLOAD FROM EXCEL</button>
<span style="display:none" id="spnName"></span>
$(function () {$("#fileupload1").change(function () {
$("#spnName").html($("#fileupload1").val().substring($("#fileupload1").val().lastIndexOf('\\') + 1));
var file = $("#spnName").html();
$.ajax({
url: "UploadExcelForContractStaff",
type: 'POST',
data: JSON.stringify({ file: file }),
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (data) {
}
});
});
});`
[AcceptVerbs(HttpVerbs.Post)]
public string UploadExcelForContractStaff(HttpPostedFileBase uploadFile)
{
StringBuilder strValidations = new StringBuilder(string.Empty);
try
{
if (uploadFile.ContentLength > 0)
{
string filePath = Path.Combine(HttpContext.Server.MapPath("../Uploads"),
Path.GetFileName(uploadFile.FileName));
uploadFile.SaveAs(filePath);
DataSet ds = new DataSet();
//A 32-bit provider which enables the use of
string ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties=Excel 12.0;";
using (OleDbConnection conn = new System.Data.OleDb.OleDbConnection(ConnectionString))
{
conn.Open();
using (DataTable dtExcelSchema = conn.GetSchema("Tables"))
{
string sheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
string query = "SELECT * FROM [" + sheetName + "]";
OleDbDataAdapter adapter = new OleDbDataAdapter(query, conn);
//DataSet ds = new DataSet();
adapter.Fill(ds, "Items");
if (ds.Tables.Count > 0)
{
if (ds.Tables[0].Rows.Count > 0)
{
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
//Now we can insert this data to database...
}
}
}
}
}
}
}
catch (Exception ex) { }
return "";
}
I got solution. changed code like
<form enctype="multipart/form-data" id="frmUplaodFileAdd">
#Html.AntiForgeryToken()
<input style="display:none" type="file" id="fileupload1" />
<button type="button" onclick='$("#fileupload1").click()'>UPLOAD FROM EXCEL</button>
<span style="display:none" id="spnName"></span>
</form>
$.ajax({
url: "UploadFile", //Server script to process data
type: 'POST',
async: false,
xhr: function () { // Custom XMLHttpRequest
var myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) { // Check if upload property exists
myXhr.upload.addEventListener('progress',
progressHandlingFunction, false); // For handling the progress of the upload
}
return myXhr;
},
data: formData,
//Options to tell jQuery not to process data or worry about content-type.
cache: false,
contentType: false,
processData: false,
success: function (data) { }
});
[HttpPost]
public ActionResult UploadFile(HttpPostedFileBase file)
{return Json();
}
I have modified original modal.js script to support ajax content as well, and added a new Behavior called "ajax" here is my piece of code:
ajax: function(callback) {
callback = $.isFunction(callback)
? callback
: function(){}
;
var $content = $(this).find('.content');
$.get("contentData.php", function(data) {
$content.html(data);
});
And I call it like:
$('body').on('click', '.domOdal', function() {
$('.ui.modal')
.modal({
observeChanges: true
}).modal('ajax')
});
The above code works perfect and loads content correclty, but I would like to extended a bit more, so I can include additional info such as custom url, dataType, etc pretty much all the ajax options, and I would like to do that from initialization part like:
$('body').on('click', '.domOdal', function() {
$('.ui.modal')
.modal({
observeChanges: true
}).modal('ajax', {"id":5}, dataType:"json", "url": http://myurl.php" etc...)
});
A bit late but this it what's working for me:
$('body').on('click', '.domOdal', function (e) {
e.preventDefault();
$('.ui.modal')
.modal({
blurring: true,
observeChanges: true,
transition: 'scale',
onVisible: function (callback) {
callback = $.isFunction(callback) ? callback : function () { };
var $content = $(this).find('.content');
$.get("contentData.php", function (data) {
$content.html(data);
});
}
}).modal('show')
});
And in your html where the modl is called:
<div class="ui modal">
<i class="close icon"></i>
<div class="content">
</div>
</div>
How about doing it like this:
$('body').on('click', '.domOdal', function() {
$.ajax({
url: "specs.html",
type: 'POST',
dataType: 'xml',
dataType: 'html'
}).done(function(response) {
console.log(response)
$(response).modal();
});
});
I'm having an issue with the jquery function submit for a form :
$(document).ready(function () {
$('#message').keydown(function(e) {
if(e.which == 13 && !e.shiftKey) {
$('#edit_message_11').submit(function() {
alert("HELLO2");
});
return false;
}
});
});
<form id="edit_message_11" class="edit_message" method="post" action="/message/11" accept-charset="UTF-8">
<textarea id="message" class="form-control edit_message_form" name="message">
Hello
</textarea>
http://jsfiddle.net/978QC/
When I do the following for my form : $('#edit_message_11').submit(function() { ... }); it doesn't trigger the submit.
However, If I do $('#edit_message_11').submit(); it does trigger the submit.
The reason why I need to do $('#edit_message_11').submit(function() { ... }); is because I want to do an ajax submit.
Anyone has a clue?
Thanks!
I don't believe it will work the way you are trying to do it. When it's inside the submit function, the alert will never fire until it gets a response back from POST. Which means you need a response from your form processing script.
Your AJAX call doesn't need to be inside the submit function, it just needs to be inside the event.
$(document).ready(function () {
$('#selfie_message').keydown(function(e) {
if(e.which == 13 && !e.shiftKey) {
$('#edit_selfie_11').submit();
$.ajax({
type: "POST",
url: "/selfies/11",
data: $("#edit_selfie_11").serialize()
});
}
});
});
If you need something to happen on success, you would do it like this.
$(document).ready(function () {
$('#selfie_message').keydown(function(e) {
if(e.which == 13 && !e.shiftKey) {
$('#edit_selfie_11').submit();
$.ajax({
type: "POST",
url: "/selfies/11",
data: $("#edit_selfie_11").serialize(),
success: function(response){
//your response code here//
}
});
}
});
});
Can any body give example to save the multipart form by using backbone js model?
How to combine the form data with file data and save to model
I am setting the model attributes and how to include the file data in the attributes. I adapted the code from one of the site to Forc Backbone to save an attribute as a file. I could not relate it to my form
<form enctype="multipart/form-data">
<input type="file" name="ImageData">
<input type="text" name="UserName">
</form>
Model
User = Backbone.Model.extend({
readAvatar : function (file, callback) {
var reader = new FileReader(); // File API object for reading a file locally
reader.onload = (function (theFile, self) {
return function (e) {
// Set the file data correctly on the Backbone model
self.set({avatar_file_name : theFile.name, avatar_data : fileEvent.target.result});
// Handle anything else you want to do after parsing the file and setting up the model.
callback();
};
})(file, this);
reader.readAsDataURL(file); // Reads file into memory Base64 encoded
}
attribute : function(attr) {
return Object.defineProperty(this.prototype, attr, {
get: function() {
return this.get(attr);
},
set: function(value) {
var attrs;
attrs = {};
attrs[attr] = value;
return this.set(attrs);
}
});
};
});
var form_data = form.serializeArray();
View
this.model.data = form_data;
var profiledata;
if (window.FormData) {
profiledata = new FormData();
console.log(profiledata);
}
if (profiledata) {
jQuery.each($('#ImageData')[0].files, function(i, file) {
//reader.readAsDataURL(file);
profiledata.append("ImageData[]", file);
});
}
this.model.ImageData = profiledata;
//and save the data
this.model.save
Rather than handling the FileReader logic in the model, I've been managing that in the view.
Check this out:
<form enctype="multipart/form-data">
<input type="file" name="ImageData">
<input type="text" name="UserName">
<button>Submit</button>
</form>
View:
var FormView = Backbone.View.extend({
events: {
"submit form" : "submit",
"change input[type=file]" : "encodeFile"
},
render: function () {
var content = this.template();
this.$el.html(content);
return this;
},
encodeFile: function (event) {
var file = event.currentTarget.files[0];
var reader = new FileReader();
reader.onload = function (fileEvent) {
this.model.set({
avatar_data: fileEvent.target.result // file name is part of the data
});
}.bind(this)
reader.onerror = function () {
console.log("error", arguments)
}
reader.readAsDataURL(file);
},
submit: function (event) {
event.preventDefault();
this.model.set({ UserName: $('input[name=UserName]').val() });
this.model.save();
}
});
I am trying to pass the object myclass to the view page, the issue I am facing is null object is being returned back to the controller. Any pointers ?
Below is the code in my ascx page
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<myclass>" %>
<div class="upModel" style="display:none">
<%= Model%>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("#load").click(function () {
try {
$.ajax({
type: "POST",
url: "Loadmyaction",
data: $("#upModel").serialize(),
contentType: "application/json; charset=utf-8",
success: function(data) {
alert(data);
},
error: function(result) { alert("Error" + result); }
});
}
catch (err) {
alert(err.description);
}
});
</script>
**On controller, this is my method**
public string Loadmyaction(string obj)
{
string str = "";
return str;
}
Here obj is getting null from the view. Why is that no data is being passed back to the controller ?
Are you sure it's actually hitting your method?
Your jquery should look like this:
$.ajax({
type: "POST",
url: "<%=Url.Action("Loadmyaction") %>",
data: $("#upModel").serialize(),
dataType: "json",
success: function(data) {
alert(data);
},
error: function(result) {
alert("Error" + result);
}
});
Try changing your parameter type to myClass, whatever it might be.
[HttpPost]
public JsonResult LoadMyAction(MyClass model)
{
return Json("someString");
}