jQuery File Upload Basic Plus Ui and i18n - internationalization

I use jQuery File Upload Basic Plus Ui for a multiple upload files. I need to display error messages in multiples languages (English, French and Spanish) but I don’t know how to create
messages: {
maxNumberOfFiles: 'Maximum number of files exceeded',
acceptFileTypes: 'File type not allowed'
maxFileSize: 'File is too large',
minFileSize: 'File is too smal
}
in multiple languages and how to declare the language for
file.error = settings.i18n('acceptFileTypes');
With the demo version, the errors messages are displayed ok.
Thanks

Here is how to instanciate fileupload plugin :
$(document).ready(function() {
$('#fileupload').fileupload({
url: 'yoururl',
acceptFileTypes: exttensionsRegex,
maxFileSize: yourmaxsize ,
maxTotalFileSize: totalsize,
maxNumberOfFiles: numberoffiles ,
messages: {
maxNumberOfFiles: 'yourText',
acceptFileTypes: 'yourText' ,
maxFileSize: 'yourText',
minFileSize: 'yourText'
}
});
});
If this javascript is generated by your server side code, then you can use the internationalization API to get the right messages and put them in place of yourText
As for :
file.error = settings.i18n('acceptFileTypes');
Actually you don't need to do anything, let it how it is and it would work.
I hope it can help

Related

Fineuploader taking too long to upload files in IE9

Hi I am using fineuploader 3.3.0 version.
I am facing problem with fineuploader in IE9. as fine uploader does not support sizeLimit in ie9.
I am checking the file size at server side with simple contentlength check if (this.Request.Files[0].ContentLength > 5242880).
but it took 1-2 mins to get this response. Also the 1.4 MB file is taking too long to upload.
Can some one please let me know what is causing it, following is the fineuploader code I am using:-
$('#restricted-fine-uploader').fineUploader({
request: {
endpoint: '/apm/api/job/UploadDocument/?category=' + JobDocuments.category + '&mode=' + JobDocuments.forceupload + '&jobid=' + job_manager_details.jobId
},
autoUpload: true,
text: {
uploadButton: 'Upload File'
},
multiple: false,
validation: {
allowedExtensions: ['doc', 'docx', 'xls', 'xlsx', 'pdf'],
sizeLimit: 5242880,
itemLimit: 1
},
showMessage: function (message) {
// Using Twitter Bootstrap's classes and jQuery selector and method
$('#restricted-fine-uploader').append('<div class="alert alert-error">' + message + '</div>');
}
}).bind('submit', function (event, id, fileName) {
$('#displaymessage').hide();
$('li. qq-upload-fail').hide();
job_manager_details.isuploading = 1;
// fileCount++;
}).bind('complete', function (event, id, fileName, responseJSON) {
$('li. qq-upload-fail').hide();
$('#displaymessage').hide();
job_manager_details.isuploading = 0;
if (responseJSON.success) {
// fileCount--;
ShowJobDocuments();
// if (fileCount == 0 && !$('div.alert-error').html()) {
$('#jobDocumentDialog').dialog("close");
// }
}
})
I just had the same issue and found one more clue.
The VM is incredibly slow (WinXP/IE8) while the network was a NAT'd but it became very fast as soon as it was switched to being bridged.
The speed of the upload should not be influenced by Fine Uploader in any noticeable way. All Fine Uploader does for non File API browsers, such as IE9 and older, is submit a <form> containing the file and related parameters. If you are noticing slow upload times, most likely something in your environment is the cause of the issue. You haven't provided any additional information about your environment, so I can't offer any advice on that front.
As you may already know, file size checking is not possible client-side in IE9 and earlier due to lack of File API support.

Extjs 4 (with a code for 3.4 below) downloading a file returned from a post request

I have seen questions slightly related to this, but none that answer my problem. I have set up an Ext.Ajax.request as follows:
var paramsStringVar = 'param1=1&param2=two&param3=something&param4=etc';
Ext.Ajax.request({
url: '/cgi-bin/url.pl',
method:'POST',
params:paramsStringVar,
timeout:120000,
success: function(response, opts){
var objhtml = response.responseText; //content returned from server side
console.log(objhtml);
}
});
This request retrieves the appropriate content from the backend. One parameter is outputType, which can take values {html, excel, csv}. When returning html to display I am able to handle and display it correctly. Now on to the problem...
When I set the outputType parameter to csv or excel, I get back the appropriate content as csv or tsv(excel) as requested. BUT, I don't want the content, I want a prompt to download the file(csv or excel). How can I have the browser auto prompt the user to download the file instead of just retrieving the text content within extjs?
Version 4.07 so I can't use any 4.1 only features
There seems to be no bulletproof solution but there are several approaches I would try:
1) Use an iframe instead of real XHR to POST data to the server, e.g. <form action="/something" target="myiframe"> where myiframe is the name of your hidden iframe. That way your form would use the iframe (not your main window) to submit data to the configured URL. Your server should set response header as application/octet-stream (or some ither MIME type for binary data) so the browser triggers download. Otherwise (if html returned in your case) you can just retrieve iframe's body innerHTML and display it to the user in UI. While using an iframe (or a new window) instead of XHR doesn't sound like the best idea, this solution seems to be the most reliable so far (and with best browser support).
Here is a slightly modified example from Ext.form.Basic docs page:
Ext.create('Ext.form.Panel', {
title: 'Basic Form',
renderTo: Ext.getBody(),
width: 350,
// Any configuration items here will be automatically passed along to
// the Ext.form.Basic instance when it gets created.
// *THIS* makes the form use a standard submit mechanism, not XHR
/**/standardSubmit: true,
// URL to submit to
url: 'save-form.php',
items: [{
fieldLabel: 'Field',
xtype: 'textfield',
name: 'theField'
}],
buttons: [{
text: 'Submit',
handler: function() {
// The getForm() method returns the Ext.form.Basic instance:
var form = this.up('form').getForm();
if (form.isValid()) {
// Submit the Ajax request and handle the response
form.submit({
success: function(form, action) {
Ext.Msg.alert('Success', action.result.msg);
},
failure: function(form, action) {
Ext.Msg.alert('Failed', action.result.msg);
},
// You can put the name of your iframe here instead of _blank
// this parameter makes its way to Ext.form.Basic.doAction()
// and further leads to creation of StandardSubmit action instance
/**/ target: '_blank'
});
}
}
}]
});
There are two key parameters here (lines marked with /**/):
standardSubmit: true config that you pass to your form will make it do a standard submit instead of XHR.
Passing a target parameter to the form's submit action. This feature is not documented but you can see it being used in Ext.form.action.Submit source code (all options that you pass to Ext.form.Basic.submit() method end up as parameters of Ext.form.action.* instance.
In the example code I put target: '_blank' to demonstrate that it works right away (will create a new browser window). You can replace it with the name of your iframe later but I suggest that you first test how your form submits data to a regular new window and then develop logic that creates and processes an iframe. You will have to process the result inside iframe yourself, thought. It's not that difficult, see Ext.data.Connection.upload() implementation as an example of iframe processing.
ExtJS actually already uses the iframe technique for file uploads. See Ext.data.Connection and Ext.form.field.Field.isFileUpload() for an idea of how it can work.
2) Suggested here: Using HTML5/Javascript to generate and save a file.
If you don't want to go the iframe way, you can try generate data URI from response data and navigate to that URI triggering download:
content = "Hello world!";
uriContent = "data:application/octet-stream," + encodeURIComponent(content);
window.location.href = uriContent;
Again, mimetype is essential here. This worked for me, you should note, however, that browsers impose a size limit to data URIs (256Kb is a safe bet).
3) Another answer in the mentioned thread links to FileSaver.js library the implements the (abandoned?) w3 spec. Usage and demo here. It uses [BlobBuilder] to generate a blob of binary data that is further used to initialize downloads using one of several methods. While this solution seems to work, it uses deprecated APIs and may not be future-proof.
Below is my solution. This is how I have it currently working. The response generates a download/open prompt, based on a response type of text/csv. Note that no iFrame or reference to an iframe are needed. I spent a lot of time hung up on the need for an iFrame, which actually broke my solution. An iFrame is not needed to generate a download prompt. What is needed is a request(submittal) similar to this one, along with a backend generating the appropriate csv with text/csv response header.
var hiddenForm = Ext.create('Ext.form.Panel', {
title:'hiddenForm',
standardSubmit: true,
url: /cgi-bin/url.pl
timeout: 120000,
height:0,
width: 0,
hidden:true,
items:[
{xtype:'hiddenField', name:'field1', value:'field1Value'},
// additional fields
]
})
hiddenForm.getForm().submit()
The standardSubmit line is vital
You don't need to create a form panel and make it hidden in your extjs file. We can add a html form and on click of button in extjs file we can submit the form using the url. This will work both in IE as well as chrome browsers. Below is my code i tried and its working fine,
<form action="<%=fullURL%>/DownloadServlet.do" method="get" id="downloadForm" name="downloadForm" target="_self">
</form>
click:
{
fn: function()
{
document.getElementById('downloadForm').submit();
}
}
To get it working on ExtJS 3.4:
var hiddenForm = new Ext.FormPanel({
id:'hiddenForm',
region: 'south',
method: 'POST',
url: "/cgi/test.wsgi",
height: 0,
standardSubmit: true,
hidden:true,
items:[
{xtype:'hidden', name:'p', value:p},
{xtype:'hidden', name:'g', value:g},
// ...
],
});
linkThis = new Ext.Button({
text: 'Download this CSV',
handler: function() {
hiddenForm.getForm().submit();
},
maxHeight: 30,
});
Remember that in order to make it working, you should put the hiddenForm in any container (i.e. in the same Ext.Window of the button), for example:
risultatiWindow = new Ext.Window({
title: 'CSV Export',
height: 400,
width: 500,
....
items: [...., hiddenForm]
});

Error handling when downloading a file from a servlet

I have a web application that must work with IE7 (yeah i know..) where the frontend is entirely made with ExtJS4, and theres a servlet used to download files. To download a file i send some parameters so i cant simply use location.href. it must be a POST.
So far it works, but when an exception is thrown in the servlet i dont know how to handle it to show the user some alert box or some message without redirecting to another page.
In my webapp im also using DWR and im aware of the openInDownload() function, but it triggers a security warning in IE.
So, (finally!) the question is
Using this code:
post = function (url, params) {
var tempForm=document.createElement("form");
tempForm.action=url;
tempForm.method="POST";
tempForm.style.display="none";
for(var x in params) {
// ...snip boring stuff to add params
}
document.body.appendChild(tempForm);
tempForm.submit();
return tempForm;
}
is it possible to stay in the same page after submitting ?
or with this other one:
Ext.Ajax.request({
url: './descargaArchivoNivs',
method: 'POST',
autoAbort: true,
params: {
nivs: jsonData
},
success: function(response){
// HERE!!
// i know this is wrong
document.write('data:text/plain,' + response.responseText );
/* this looked promising but a warning pops up
var newwindow = window.open();
newwindow.document.open();
newwindow.document.write('data:text/plain, ' + response.responseText );
newwindow.document.close();*/
},
failure: function(resp){
alert('There was an error');
}
});
is it possible to open the file download dialog // HERE!! with the response content??
or is there some other way to open the file download dialog on success, and on failure show a friendly message without losing the users input (the params of the POST) ?
(sorry if this post was too long)

Sencha Error XMLHttpRequest cannot load http://localhost.... Origin null is not allowed by Access-Control-Allow-Origin

I'm having a problem with loading a Sencha store. My store declaration is like this:
Ext.regModel('Car',{
idProperty: 'id',
fields: [
//'id', 'company', 'driver', 'carType','xCoordinate','yCoordinate'
{name: 'id', type: 'int'},
{name:'company', type:'string'} ,
{name:'driver', type:'string'},
{name:'carType', type:'string'},
{name:'xCoordinate', type:'int'},
{name:'yCoordinate', type:'int'}
]
});
var strr= new Ext.regStore({
id:'carStore',
model:'Car', //configuration option is the cars
proxy: {
type: 'ajax',
url: 'http://localhost:8080/A/carStore.html&callback=?',
reader: {
type: 'json',
root: 'carss'
},
},
autoLoad: true
});
And I'm keeping the store in a list:
CarManagementSystem.views.carList = new Ext.List({
id: 'carList',
store: 'carStore',
onItemDisclosure: function (record) {
var selectedCar = record;
CarManagementSystem.views.addNewCar.load(selectedCar);
CarManagementSystem.views.viewport.setActiveItem('addNewCar', { type: 'slide', direction: 'left' });
},
itemTpl: '<div class="list-item-id">{id}</div>' +'<div class="list-item-driver">{driver}</div>'
});
However, when I try to load the list with my JSON file, I get this error:
XMLHttpRequest cannot load http://localhost:8080/A/carStore.html&callback=?&_dc=1311751412006&limit=25. Origin null is not allowed by Access-Control-Allow-Origin.
sencha-touch-debug.js:7212
Uncaught TypeError: Cannot read property 'length' of undefined
I'm keeping my JSON file in an html format and it is kept in the server. I'd appreciate any help.
Thanks!
You are encountering the classic CORS issue.
It's a browser security, called web-security. If you are in dev mode, you can run Chrome and disabling this flag. But if you run your app in production on a browser, you will need to bypass this ajax specification restriction.
To bypass it, you can use proxys (such as creating a back-end script on the same domain will load for you the resource) or you can use JSON-P. For this you will need to change your store to a script tag BUT ALSO you will need the server to be able to detect a callback param and send it to you as a JS function automatically executed when inserted in the DOM.
I will add that you won't have this issue when running in Phonegap because PhoneGap is not running a web server but serves files with the file:// protocol.
If you want to learn more, and I recommand as it is a common pb when developing mobile web apps, you should learn what JSON-P is, what CORS is, and how it works.
You can't hit a port number (8080) when making an AJAX request. If you end up needing a cross-domain request change your proxy type to 'scripttag'.
You should change the proxy type from 'ajax' to 'type: 'scripttag'

Upload files asynchronously (AJAX) with HTTP/1.1 PUT method, why not?

Uploading files via PUT method, even binary or text, via a "normal web browser" is possible.
Why many people are just saying, that is not possible ?
Sample code with jQuery and PHP.
$(document).ready(function() {
$("#uploadbutton").click(function() {
var filename = $("#file").val();
$.ajax({
type: "PUT",
url: "addFile.do",
enctype: 'multipart/form-data',
data: {file: filename},
success: function(){
alert( "Data Uploaded: ");
}
});
});
});
On the server side just read the STDIN stream like
<?php
/* PUT data comes in on the stdin stream */
$putdata = fopen("php://input", "r");
/* Open a file for writing */
$fp = fopen("myputfile.ext", "w");
/* Read the data 1 KB at a time
and write to the file */
while ($data = fread($putdata, 1024))
fwrite($fp, $data);
/* Close the streams */
fclose($fp);
fclose($putdata);
?>
{file: filename}
When you upload a file, you have to upload the file. Telling the server what the local filename is… isn't enough.
JavaScript, running in a web browser in a standard security context, doesn't have access to read the data in the file from the user's hard disk.
Since you can't get the data, you can't upload it.
For your solution specifically, mainly because the PUT method (verb) is not supported by all browsers, especially older ones, so this solution won't work for everyone.
The topic has come up previously as well, though not exactly the same, some answers are examples of where PUT and DELETE don't work.
The documentation for $.ajax() mentions this as well:
type
Default: 'GET'
The type of request to make ("POST" or "GET"), default is "GET".
Note: Other HTTP request methods, such as PUT and DELETE, can also be used here, but they are not supported by all browsers.

Resources