iframe onloads before the time when file uploads - ajax

I'm trying to upload file on server by submitting the form and return information about file upload status in iframe. The problem is that iframe onloads before the time when file uploads...
Here is my JS:
var resp;
function doAjaxPost()
{
$.ajax({
Accept: "text / html, application / xhtml + xml, application / xml; q = 0.9, image / webp, * /*;q=0.8",
contentType: "application/x-www-form-urlencoded",
type: "POST",
url: some_uri,
data: some_data,
success: function (response)
{
var recordid = response.substring(response.indexOf('<span id="st_id"></span>') + '<span id="st_id"></span>'.length, response.indexOf('<span id="fin_id"></span>'));
$("#photo").attr("action", "/uploadmyshowcase?table=enmyshowcase&field=enf_photow&id=" + recordid);
$("#photo").submit();
resp = response;
}
} );
function frameCheck(frm)
{
var frmDoc = frm.contentDocument || frm.contentWindow.document;
var field;
if (frmDoc.body.innerHTML && /You successfully uploaded file/.test(frmDoc.body.innerHTML))
{
$('#list').html(resp.substring(resp.indexOf('<span id="st_list"></span>'), resp.indexOf('<span id="fin_list"></span>')));
// Here I replace the part of the current page when file uploaded by placing the <img>-tag with the link on uploaded file.
}
}
Here is my HTML:
<div class="col-md-8" >
<form id="photo" method="POST" action="" target="result" enctype="multipart/form-data" accept-charset="UTF-8">
<input class="noreq input_file" type="file" name="file">
<input class="noreq input_file" style="display:none" type="text" name="name">
</form>
</div>
<iframe class="hidden" id="res" name="result" onload="frameCheck(this)"></iframe>
Here is my upload controller:
#RequestMapping(value = "/uploadmyshowcase", method = RequestMethod.POST)
public #ResponseBody
String uploadFileController(#RequestParam("name") String name,
#RequestParam("file") MultipartFile file,
#RequestParam(value = "table", required = false) String table,
#RequestParam(value = "field", required = false) String field,
#RequestParam(value = "id", required = false) String Id,
Model model) {
if (!file.isEmpty()) {
try {
byte[] bytes = file.getBytes();
File dir = new File("D:\\NetBeansProjects\\bar\\src\\main\\webapp\\resources\\rcvdFiles");
if (!dir.exists()) {
dir.mkdirs();
}
String[] ext;
if (file.getOriginalFilename().contains(".")) {
ext = file.getOriginalFilename().toString().split("\\.");
if (!"jpg".equals(ext[1]) && !"jpeg".equals(ext[1])) {
return "Wrong format~" + field;
}
} else {
return "Wrong format~" + field;
}
File serverFile = new File(dir.getAbsolutePath() + File.separator + table + "-" + field + "-" + Id + "." + ext[1]);
BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
stream.write(bytes);
stream.close();
String href = "";
switch (field) {
case "enf_photow":
if (new File(dir.getAbsolutePath() + File.separator + table + "-" + field + "-" + Id + "." + ext[1]).exists()) {
href = "/resources/rcvdFiles/" + table + "-" + field + "-" + Id + "." + ext[1];
}
break;
}
return "You successfully uploaded file~" + field + "~" + href + "~" + Id;
} catch (Exception e) {
return "Wrong format~" + field;
}
} else {
return "Wrong format~" + field;
}
As result I see, that frameCheck() is calling before the time when file uploaded on the server. And the IMG that I placing programmatically on page is empty and console says, that Resource not found... What's wrong?
Thank You.
EDIT
I tried to create iframe programmatically, but still I have the same result :(
My modified JS:
$.ajax({
Accept: "text / html, application / xhtml + xml, application / xml; q = 0.9, image / webp, * /*;q=0.8",
contentType: "application/x-www-form-urlencoded",
type: "POST",
url: uri,
data: ctrls,
success: function (response) {
var recordid = response.substring(response.indexOf('<span id="st_id"></span>') + '<span id="st_id"></span>'.length, response.indexOf('<span id="fin_id"></span>'));
if(!del)
{
var iframe = document.createElement("iframe");
iframe.name = "result";
iframe.setAttribute('id', "res");
document.body.appendChild(iframe);
$("#photo").attr("action", "/uploadmyshowcase?table=enmyshowcase&field=enf_photow&id=" + recordid);
$("#photo").prop("target", "result");
$("#photo").submit();
resp = response;
$("#res").load(function() {
frameCheck($("#res"));
});
}
}
} );
My modified HTML:
<form id="photo" method="POST" action="" enctype="multipart/form-data" accept-charset="UTF-8">
<input class="noreq input_file" type="file" name="file">
<input class="noreq input_file" style="display:none" type="text" name="name">
</form>

The issue is because iframe's onload does not wait for the ajax to be done. That's the reason you are running into that issue. You can alter your code to below get it called after ajax response is returned. Give it a try. This should give you the gist of it.
function doAjaxPost()
{
$.ajax({
Accept: "text / html, application / xhtml + xml, application / xml; q = 0.9, image / webp, * /*;q=0.8",
contentType: "application/x-www-form-urlencoded",
type: "POST",
url: some_uri,
data: some_data,
success: function (response)
{
var recordid = response.substring(response.indexOf('<span id="st_id"></span>') + '<span id="st_id"></span>'.length, response.indexOf('<span id="fin_id"></span>'));
$("#photo").attr("action", "/uploadmyshowcase?table=enmyshowcase&field=enf_photow&id=" + recordid);
$("#photo").submit();
resp = response;
// set and call your iframe onload function here. You can also create your iframe here, if just setting your onload does not work.
$("#res").onload = frameCheck($("#res"));
}
} );
Remove onload from iframe.
<div class="col-md-8" >
<form id="photo" method="POST" action="" target="result" enctype="multipart/form-data" accept-charset="UTF-8">
<input class="noreq input_file" type="file" name="file">
<input class="noreq input_file" style="display:none" type="text" name="name">
</form>
</div>
<iframe class="hidden" id="res" name="result" "></iframe>

Related

How to pass #ModelAttribtue to Controller and call POST method to insert the data in spring mvc using ajax call

I am using jstl and I need to get back the id upon insertion to jsp from controller. To achieve that I am using ajax and I am unable to pass the modelAttribute of the form.
JSP
<form:form method="POST" action="addCountry.html" name="form" modelAttribute="countryMaster" id="addCountryForm">
<div class="box-body">
<div class="row">
<div class="col-md-6">
<div class="form-group has-feedback" id="countryNameDiv">
<form:label path="countryName" for="countryName">Country Name</form:label>
<form:input placeholder="Enter country Name" path="countryName"
class="form-control" name="countryName"
value="${countryMaster.countryName}" required="true"
data-error="country Name cannot be empty" />
<form:errors path="countryName" cssClass="text-red" />
<div class="help-block with-errors"></div>
</div>
</div>
</div>
</div>
<div class="box-footer">
<form:button type="button" onclick="window.location.reload()" class="btn pull-left btn-primary">Clear</form:button>
<div class="pull-right">
<button onclick="submitTheForm()" class="btn btn-primary">Add Country</button>
Cancel
</div>
</div>
</form:form>
AJAX
function submitTheForm(){
var value = $("#addCountryForm").serialize();
$.ajax({
type : "post",
url : 'addSaveCountry.html',
dataType: "json"
data : {
countryMaster : value
},
success: function(result){
console.log(result);
if(resule.localeCompare("Some exception occured, try again.") == 0) {
/**
* Give a div where you display this message
**/
} else if(result.localeCompare("New Country Inserted")) {
var alert = "<div class=\"alert alert-success alert-dismissible\" role=\"alert\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-label=\"Close\"><span aria-hidden=\"true\">x</span>";
alert += "</button>";
alert += "<strong>"+result+"!</strong>";
alert += "</div>";
var informationDiv = alert + "<br>";
document.getElementById("informationDiv").innerHTML = informationDiv;
} else {
var alert = "<div class=\"alert alert-success alert-dismissible\" role=\"alert\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-label=\"Close\"><span aria-hidden=\"true\">x</span>";
alert += "</button>";
alert += "<strong>"+result+"!</strong>";
alert += "</div>";
var informationDiv = alert + "<br>";
document.getElementById("informationDiv").innerHTML = informationDiv;
}
}
});}
Controller Code
#RequestMapping(value="/addSaveCountry", method = RequestMethod.POST)
public #ResponseBody String addCountryPost(#Validated #ModelAttribute("countryMaster") Country country, BindingResult result){
try {
if (result.hasErrors()) {
Gson gson = new Gson();
String json = gson.toJson("Some exception occured, try again.");
return json;
}
int companyId = 1;
country.setCompanyId(companyId);
String createdBy, lastUpdatedBy;
createdBy = "IN129";
lastUpdatedBy = "IN129";
country.setCreatedBy(createdBy);
country.setLastUpdatedBy(lastUpdatedBy);
java.sql.Timestamp curTime = new java.sql.Timestamp(new java.util.Date().getTime());
country.setCreatedDate(curTime);
country.setLastUpdatedDate(curTime);
boolean status = countryService.addorupdateCountry(country);
if (status == true) {
Gson gson = new Gson();
String json = gson.toJson("New Country Inserted");
return json;
} else {
Gson gson = new Gson();
String json = gson.toJson("New Country Insertion Failed, Try Again Later");
return json;
}
}}
When I run it and try to insert, I am getting
"HTTP Status 405 - Request method 'POST' not supported"
message - Request method POST not supported
description - The specified HTTP method is not allowed for the requested resource.
Thanks in advance.
Change your URL from html suffix :
url : 'addSaveCountry.html',
To Path of RequestMapping
url : '/addSaveCountry',
also change to type: "POST" (uppercase)

Save form data into database and upload file into dropbox in node.js express

I want to save my form data into database and upload same form file into dropbox.
I could upload files into dropbox separately using formidable, I couldn't combine the both.
Thanks in advance!!
HTML Form:
<form id="content" enctype="multipart/form-data" method="post">
<fieldset>
<legend>New Content</legend>
title : <input type="text" name="tit" id="tit"/><br><br>
category : <input type="text" name="cat" id="cat"/><br><br>
description : <input type="text" name="des" id="des"/><br><br>
file : <input type="file" name="file" id="file"/><br><br>
<input type="submit" value="Submit" name="submit"><br><br>
<div class="resu"></div>
</fieldset>
</form>
Ajax Request:
$(document).ready(function() {
$('#content').submit(function(event) {
var title = $('input[name=tit]').val();
var category = $('input[name=cat]').val();
var desc = $('input[name=des]').val();
var file = $('input[name=file]').val();
var filename = file.split("\\").pop();
$.ajax({
type : 'POST',
url : 'http://127.0.0.1:8081/addContent',
data : {"user_id": 12, "title": title, "description": desc, "category": category, "file_name": filename},
dataType : 'application/json',
encode : true,
})
.done(function(data) {
//$(.result).html(data);
console.log(data);
});
event.preventDefault();
});
});
Node.Js File
router.post("/", function(req, res){
var form = new formidable.IncomingForm();
form.parse(req, function(err, fields, files) {
//console.log(files);
// `file` is the name of the <input> field of type `file`
var temp_path = files.file.path,
file_type = files.file.type,
file_name = files.file.name;
//new_path = 'uploads/';
node_dropbox.Authenticate(app_key, app_secret, 'redirect_url', function(err, url){
//console.log(url);
});
node_dropbox.AccessToken(app_key, app_secret, 'access_code', 'redirect_url', function(err, body) {
var access_token = body.access_token;
var token = token;
var api = node_dropbox.api(token);
fs.readFile(temp_path, function(err,content){
if(!err){
request.put('https://api-content.dropbox.com/1/files_put/auto/files/upload/' + file_name, {
headers: {Authorization: 'Bearer ' + token, 'Content-Type': file_type},
body: content},
function optionalCallback(err, httpResponse) {
if (err) {
console.log('Not Uploaded');
res.end();
}
else {
console.log("Uploaded Successfully");
var query="INSERT INTO kind_heart.contents(user_id, title, category, description, content_status, date_time, file_name) VALUES(?,?,?,?,'Uploaded',NOW(),?)";
var datafromjson = [req.body.user_id, req.body.title, req.body.category, req.body.description, req.body.file_name];
console.log("SQL Query: " + query);
connection.query(query, datafromjson, function(err, rows, fields) {
if(err){
console.log(err);
console.log("Error: Not Uploaded");
res.end("Error: Not Uploaded");
}else{
//res.writeHead(200, {'Content-Type': 'application/json'});
var result = JSON.stringify(rows);
res.end(result);
console.log("Uploaded Succesfully!!");
}
});
res.end();
}
});
}
});
});
});
});

Django Jquery Form no AJAX request

After reading other questions on similar subject, I still do not understand what's wrong with this code.
I am testing a code that uses Jquery Form plugin. I added a call in the view to the template, to display it for 1st time so user can select file and upload. But it never sends the AJAX request, hence the code section in view is not executed. Although not shown here, jQuery library and the jQueryForm plugin are indeed being called.
Template:
<form id="uploadForm" method="post" enctype="multipart/form-data">
{% csrf_token %}
<input id="fileInput" class="input-file" name="upload" type="file">
{{ form.docfile }}
<span class="upload-message"></span>
<input type="submit" value="Upload" />
</form>
<script>
var message = '';
var options = {
type: "POST",
url: '/upload/file/',
error: function(response) {
message = '<span class="error">We\'re sorry, but something went wrong. Retry.</span>';
$('.upload-message').html(message);
$('fileInput').val('');
},
success: function(response) {
message = '<span class="' + response.status + '">' + response.result + '</span> ';
message = ( response.status == 'success' ) ? message + response.fileLink : message;
$('.upload-message').html(message);
$('fileInput').val('');
}
};
$('#uploadForm').ajaxSubmit(options);
</script>
View:
def upload(request):
response_data = {}
if request.method == 'POST':
if request.is_ajax:
form = UploaderForm(request.POST, request.FILES)
if form.is_valid():
upload = Upload(
upload=request.FILES['upload']
)
upload.name = request.FILES['upload'].name
upload.save()
response_data['status'] = "success"
response_data['result'] = "Your file has been uploaded:"
response_data['fileLink'] = "/%s" % upload.upload
return HttpResponse(json.dumps(response_data), content_type="application/json")
response_data['status'] = "error"
response_data['result'] = "We're sorry, but kk something went wrong. Please be sure that your file respects the upload conditions."
return HttpResponse(json.dumps(response_data), content_type='application/json')
else:
form = UploaderForm()
return render(request, 'upload.html', {'form': form})
It does call template correctly during first time, it displays buttons, it executes the script again but the form is not valid, so response_data is with error.
What am I missing?
Thanks, Ricardo
You can try using the example from API section instead, just look at the source code:
$('#uploadForm').ajaxForm({
beforeSubmit: function(a,f,o) {
$('.upload-message').html('Submitting...');
},
success: function(data) {
$('.upload-message').html('Done!');
}
});
and the HTML:
<form id="uploadForm" action="/upload/file/" method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="hidden" name="MAX_FILE_SIZE" value="100000">
File: <input type="file" name="file">
{{ form.docfile }}
<span class="upload-message"></span>
<input type="submit" value="Upload" />
</form>
How it is supposed to be worked if there are no form data send in your script.
var options = {
type: "POST",
url: '/upload/file/',
data: new FormData(document.getElementById('uploadForm')),
processData: false,
contentType: false,
error: function(response) {
message = '<span class="error">We\'re sorry, but something went wrong. Retry.</span>';
$('.upload-message').html(message);
$('fileInput').val('');
},
success: function(response) {
message = '<span class="' + response.status + '">' + response.result + '</span> ';
message = ( response.status == 'success' ) ? message + response.fileLink : message;
$('.upload-message').html(message);
$('fileInput').val('');
}
};
You have at least one problem with you view - this:
if not request.GET:
return render(request, 'upload.html')
will prevent further execution when request.GET is empty which is the case when doing a POST request.

Video file upload in mvc 3 using ajax

Hi I tried to save image path in my database and retrieve it to my view to display image using the code below. Which is running perfectly. My problem now is how can I save video file using ajax? I used ajax because I'm not only saving images but I also have different data to save. e.g Name,code,blurb,synopsis etc. Thank you in advance for helping me.
In my view:
<tr>
<td>
Poster Homepage
</td>
<td style>
<form id="file_upload" action="/Movies/UploadFiles" method="POST" enctype="multipart/form-data">
<div class="fileupload-buttonbar">
#*<div class="progressbar fileupload-progressbar">
</div>*#
<div id="file_name">
</div>
<div id="file_type">
</div>
<div id="file_size">
</div>
<div id="show_image"></div>
<span class="fileinput-button"><a href="javascript:void(0)" class="upload-image">
Upload image</a>
<input type="file" name="files[]" multiple id="file" />
</span>
</div>
</form>
</td>
</tr>
script
$(document).ready(function () {
$('.progressbar').progressbar({ value: 0 });
$('#file_upload').fileupload({
dataType: 'json',
url: '/Movies/UploadFiles',
progressall: function (e, data) {
$(this).find('.progressbar').progressbar({ value: parseInt(data.loaded / data.total * 100, 10) });
},
done: function (e, data) {
$('#file_name').html(data.result.name);
$('#file_type').html(data.result.type);
$('#file_size').html(data.result.size);
$('#show_image').html('<img src="/home/image/' + data.result.name + '" />');
$('#file_name').css({ display: 'none' });
$('#file_type').css({ display: 'none' });
$('#file_size').css({ display: 'none' });
//visibility: hidden;
$(this).find('.progressbar').progressbar({ value: 100 });
}
});
Controller:
public FilePathResult Image()
{
string filename = Request.Url.AbsolutePath.Replace("/home/image", "");
string contentType = "";
var filePath = new FileInfo(Server.MapPath("~/Images") + filename);
var index = filename.LastIndexOf(".") + 1;
var extension = filename.Substring(index).ToUpperInvariant();
// Fix for IE not handling jpg image types
contentType = string.Compare(extension, "JPG") == 0 ? "image/jpeg" : string.Format("image/{0}", extension);
return File(filePath.FullName, contentType);
}
[HttpPost]
public ContentResult UploadFiles()
{
var r = new List<UploadHomePage>();
foreach (string file in Request.Files)
{
HttpPostedFileBase image = Request.Files[file] as HttpPostedFileBase;
if (image.ContentLength == 0)
continue;
string savedFileName = Path.Combine(Server.MapPath("~/Images"), Path.GetFileName(image.FileName));
image.SaveAs(savedFileName);
r.Add(new UploadHomePage()
{
Name = image.FileName,
Length = image.ContentLength,
Type = image.ContentType
});
}
return Content("{\"name\":\"" + r[0].Name + "\",\"type\":\"" + r[0].Type + "\",\"size\":\"" + string.Format("{0} bytes", r[0].Length) + "\"}", "application/json");
}
Model:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace BookingCMS.Models
{
public class UploadHomePage
{
public string Name { get; set; }
public int Length { get; set; }
public string Type { get; set; }
}
}
You could pass additional parameters with the FileUpload plugin using the formData setting:
$('#file_upload').fileupload({
dataType: 'json',
url: '/Movies/UploadFiles',
formData : {
name: 'this is the name of the movie',
synopsis: 'this is the synopsis of the movie',
type: 'movie'
},
progressall: function (e, data) {
...
},
done: function (e, data) {
...
}
});

ajaxupload el is undefined

i haved trying to use ajax upload image. here is my code
$(function () {
var btnUpload = $('#post_pd_thumnail');
if ($("#id").val()) var post_id = $("#id").val();
else var post_id = 0;
new AjaxUpload(btnUpload, {
action: site_root_domain + "/product/upload_image/" + post_id,
name: 'file_upload',
onSubmit: function (file, ext) {
if ($('#post_pd_thumnail').val() != '') {
if (!(ext && /^(jpg|png|jpeg|gif)$/.test(ext))) {
jAlert(lang_error_upload_avatar, lang_alert_notice);
return false;
}
}
$('#preview').html('<img style="margin-left:45px;margin-top:45px;" border="0" width="16" height="11" src="' + site_root_domain + '/templates/images/icons/loading_2.gif" />');
},
onComplete: function (file, response) {
if (!response) {
jAlert(lang_error_upload_avatar, lang_alert_notice);
} else {
img_upload = 1;
$('#preview').html(response);
}
return;
}
});
});
And my HTML is:
<div id="preview">{$preview}</div>
<div class="fileupload">
<input type="file" name="post_pd_thumnail" id="post_pd_thumnail" value="" />
</div>
<input type="hidden" name="id" id="id" value="{$data['product']['post_id']}" />
and i got this error when upload image "el is undefined" and the function does not work correctly can anyone help me solve this problem please
Try to change the file element to button like,
<div class="fileupload">
<input type="button" name="post_pd_thumnail" id="post_pd_thumnail" value="" />
</div>
Here is the solution.
* Attaches event to a dom element
*/
function addEvent(el, type, fn){
// 610 BUG
if (el == undefined) return;
if (w.addEventListener){
el.addEventListener(type, fn, false);
} else if (w.attachEvent){
var f = function(){
fn.call(el, w.event);
};
el.attachEvent('on' + type, f)
}
}

Resources