Parse files in FileList object - java

I am using FormData to upload multiple files in my grails project.The files needs to be uploaded via Ajax. I have used following code for ajax upload. But in controller, I get the params as [object FileList]. How do I get files from this object. Is there any way to change this object to multipart?
jQuery('#file-save').click(function() {
if (jQuery('#form input[type="file"]')) {
var form = jQuery("#form").find('input[type="file"]');
var picData = new FormData();
picData.append('userFiles', form.get(0).files);
picData.append('userId', '$usrId');
jQuery.ajax({
url: '/file/upload',
type: 'post',
dataType:'json',
data: picData,
enctype: "multipart/form-data",
contentType: false,
processData: false,
success: function(data) {
console.log("success");
}
});
}
});
The controller code is:
def upload(){
def userId = params.userId
def inputFile = params.userFiles
println(inputFile)
inputFile.each{i,j->
println(i)
println(j)
}
}
When I debug, I get params.userFiles : "[object FileList]". Any insights would be appreciated.

You most likely need to loop through the files client side, adding the same key for each one
var picData = new FormData();
// loop through form.get(0).files
picData.append('userFiles', file);
// end loop
picData.append('userId', '$usrId');

Related

Alfresco workflow activiti: How can I populate webservice result in dropdown

I am using Alfresco Community Edition-5.1.x , we created advanced workflow. In workflow we are trying to populate web-service results values in drop-down. Can you please guide us how to populate values in drop-down?
On this sample code, I'm loading the group members into dropdown control by calling Alfresco Repo webscript.
Register the control here(in ftl file)
<label for="${fieldHtmlId}">${field.label?html}:<#if field.mandatory><span class="mandatory-indicator">${msg("form.required.fields.marker")}</span></#if></label>
<select name="${field.name}" id="${fieldHtmlId}" value="${field.value?html}" style="width: 250px;"></select>
Callback method once the data is received from the REST service
<script type="text/javascript">
function ${grpName}_loadDropDown(o){
var selectElem = YAHOO.util.Dom.get("${fieldHtmlId}");
selectElem.options.length=0;
for (; i<o.json.data.length; i++){
var user = o.json.data[i];
selectElem.options[j] = new Option(user.displayName, user.shortName, false, false);
j++;
}
}
Call the REST service here
function ${grpName}_loadData(){
var url = Alfresco.constants.PROXY_URI+"api/groups/${grpName}/children?sortBy=displayName&maxItems=100&skipCount=0";
<#if field.control.params.sortAsc?exists>
<#assign sort=field.control.params.sortAsc?html>
url+="&sortAsc=${sort}";
</#if>
Alfresco.util.Ajax.request({
url: url,
method: "GET",
requestContentType: "application/json",
successCallback:{
fn: function(o){
${grpName}_loadDropDown(o);
},
scope: this
},
failureCallback:{
fn: function(o){alert("Unable to find group or error ");},
scope: this
}
});
}
Start the REST service request here
${grpName}_loadData();
</script>
Here is the sample for you and I've the following open JSON - RSET web services
to get the data.
WebService URL : https://jsonplaceholder.typicode.com/posts
The result should be something similar to the below one,
Please let me know, if you need further help on this.
<script type="text/javascript">
function ${groupName}_populateSelectData(o){
var selectElem = YAHOO.util.Dom.get("${fieldHtmlId}");
selectElem.options.length=0;
var i = 0;
var j = i+1;
for (; i<o.json.length; i++){
selectElem.options[j] = new Option(o.json[i].title, o.json[i].title, false, false);
j++;
}
}
function ${groupName}_updateList(){
var url = "https://jsonplaceholder.typicode.com/posts";
Alfresco.util.Ajax.request({
url: url,
method: "GET",
requestContentType: "application/json",
successCallback:{
fn: function(o){
${groupName}_populateSelectData(o);
},
scope: this
},
failureCallback:{
fn: function(o){alert("Error ");},
scope: this
}
});
}
${groupName}_updateList();
</script>

jquery error sending array of Strings to Spring application

I am trying to send an array of strings to a java/spring backend solution and after trying to do it in many ways I gave up cause I always have errors (malformed request, missing body...)
I am pretty surprised cause followed many examples without success. I am sure the problem is in the jquery side cause I changed the method to GET in order to see the request as clear as possible and I saw the data is not represented as expected.
This is the function:
function duplicateSection() {
var table = document.getElementById("tbody");
var ids = [];
var i = 0;
var totalRows = table.rows.length;
for(i; i < totalRows; i++){
var checkbox = table.rows[i].cells[0].children[0];
if(checkbox.checked){
var id = table.rows[i].cells[1].children[0].value;
ids.push(id);
}
}
var jsonString = JSON.stringify(ids);
alert(jsonString);
$.ajax({
url: './duplicatesections',
type: 'GET',
contentType: "application/json; charset=utf-8",
dataType: "json",
data: jsonString,
success: function(data) {
alert('sent');
}
});
}
When I show with alert the JSON string I get the expected result: ["1"]
When the request is sent I get this other result: http://localhost:8080/duplicatesections?[%221%22]
Why do I have this representation?: [%221%22]
As an extra information, I am using spring boot and thymeleaf in case it is relevant.
send a POST request.
$.ajax({
url: './duplicatesections',
type: 'POST',
contentType: "application/json; charset=utf-8",
dataType: "json",
data: jsonString,
success: function(data) {
alert('sent');
}
});

AngularJS + Spring + REST -- sending multiple files and data

i have a little problem... i cant upload multiple files to my server, pls look at my code:
in Spring context:
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
</bean>
in Spring controller
#RequestMapping(value = "/address-to-add-object/add", method = RequestMethod.POST)
public void addObject(#RequestParam(value = "files", required = false) MultipartFile[] files, #RequestParam("formDataJson") String formDataJson) {
//-- my stuff with formDataObject and uploaded files
}
in Angular controller
$scope.sendForm = function(){
var formData = new FormData();
formData.append('formDataJson', JSON.stringify($scope.myObject));
var files = $("#file-0a").prop('files');
var filesArray = [];
for (var i = 0 ; i < files.length ; i ++){
filesArray.push(files[i]);
}
formData.append('files', filesArray);
ObjectService.add(formData).$promise.then(function () {
Notification.info('success');
}, function () {
Notification.error('error');
});
};
in ObjectService
objectService.factory('ObjectService', ["$resource", function($resource) {
var baseUrl = './address-to-add-object';
return $resource(baseUrl, {},
{
add: {
url: baseUrl + '/add',
headers: {
'Content-Type': undefined
},
transformRequest: angular.identity,
method: 'POST'
}
});
}]);
and request content:
------WebKitFormBoundaryNhBUQjEH2kAlVlog
Content-Disposition: form-data; name="formDataJson"
{---json object---}
------WebKitFormBoundaryNhBUQjEH2kAlVlog
Content-Disposition: form-data; name="files"
[object File],[object File],[object File]
------WebKitFormBoundaryNhBUQjEH2kAlVlog--
and error from console
POST http://localhost:8080/project/address-to-add-object/add 500 (Internal Server Error)
and now description of my problem ;)
I can easily send one file and some data, but when i want to send multiple files a have error like above or 'files' variable is empty. I tried with List <>, wrap to bean, and cant intercept fileList object (when send $("#file-0a").prop('files')) from ajax request (or array of files when send filesArray).
Can you help me with that, do you have any ideas what can I do?
problem was on sendig files - or not sending, because as you can see sended was toString of files
[object File],[object File],[object File]
i had to change appedning of files to my FormData object:
var formData = new FormData();
formData.append('formDataJson', JSON.stringify($scope.touristObject));
var files = $("#file-0a").prop('files');
for (var i = 0 ; i < files.length ; i ++){
formData.append('files', files[i]);
}
and on Spring Controller side without any changes

Posting two textbox values through ajax

I have some problem to post 2 items namely 'content', 'content1'. 'content' is successfully posted. But 'content1' is showing as undefined index. I have tried the below code. The lines containing 'content1' is made as comments line before posting here. Please indicate my mistakes.
$(function() {
$(".submit_button").click(function() {
var textcontent = $("#content").val();
//var textcontent1 = $("#content1").val();
var dataString = 'content='+ textcontent;
//var dataString1 = 'content1='+ textcontent1;
if(textcontent=='')
{
alert("Enter some text..");
$("#content").focus();
//$("#content1").focus();
}
else
{
$("#flash").show();
$("#flash").fadeIn(400).html('<span class="load">Loading..</span>');
$.ajax({
type: "POST",
url: "action.php",
data: dataString,
// data1: dataString1,//dataString1,
cache: true,
success: function(html){
$("#show").after(html);
document.getElementById('content').value='';
//document.getElementById('content1').value='';
$("#flash").hide();
$("#content").focus();
//$("#content1").focus();
}
});
}
return false;
});
});
Oof - you should really indent your code!
That said - in your current code, you have the following lines commented out:
//var textcontent1 = $("#content1").val();
//var dataString1 = 'content1='+ textcontent1;
Which, yeah, those things aren't being set.
Uncomment those, and then pass the data as an object, like so:
$.ajax({
type: "POST",
url: "action.php",
data: {
'dataString' : dataString,
'dataString1' : dataString1,
},
cache: true,
// etc.
action.php will then receive those two strings as $_POST['dataString'] and $_POST['dataString1'].

Passing javascript variable to servlet [duplicate]

This question already has answers here:
How should I use servlets and Ajax?
(7 answers)
Closed 6 years ago.
How can I pass a var from javascript to a servlet. Yes I know you can use getParameter on the servlet side, but I first need to do some javascript stuff then from there it need to pass that new variable to servlet.
See my Javascript example:
function openBrWindowAndSubmit() {
var textBodyValue = encodeURIComponent(document.getElementById("textBody").value);
alert(textBodyValue); //returns empty
document.forms[0].submit();
var textBodyValue = encodeURIComponent(document.getElementById("textBody").value);
alert(textBodyValue); //works
}
As you can see in above example the first "alert" block returns empty, but the second one returns the correct encoded value because the document.forms[0].submit is already called. So is there a way I can get the second variable "textBodyValue" (which is outside of document.forms[0].submit) to the servlet? I'm calling this at the servlet side:
String test = req.getParameter("textBody");
Here's the JSP inside a form tag which calls the function on click:
<textarea id="textBody" name="textBody"></textarea>
<input type="button" onClick="openBrWindowAndSubmit();" value="Click Here to Preview Email">
Is there any workaround to this problem?
I've been trying to change the javascript function to:
function openBrWindowAndSubmit() { //v2.0
document.forms[0].target = "_blank";
document.getElementById("action").value = "view_template";
var textBodyValue = encodeURIComponent(document.getElementById("textBody").value);
alert(textBodyValue);
document.forms[0].submit();
var textBodyValue = encodeURIComponent(document.getElementById("textBody").value);
alert(textBodyValue);
$.ajax({
url: 'http://localhost:8080/restricted/comm/Email',
data: textBodyValue,
// processData: false,
// contentType: false,
type: 'POST',
success: function(data){
alert(data);
}
});
}
Can this work? i'm getting an undefined error when reaching the $ajax tag?
As an idea. Dont know if its correct ;) but you can check it at the jQuery api page.
$('#idOfTheForm').on('submit', function(e){
e.preventDefault();
data = { key : val , key2 : val2 };
$.ajax({
type: "post",
data: data,
url : "",
success : function(response){
console.log("return code was 200");
},
error : function(jqXHR, textStatus, errorThrown){
console.log(errorThrown);
}
});
return false;
}

Categories