HTML5 FormData file upload with RubyOnRails - ruby-on-rails

I using this script to upload file (one by one) with HTML5 FormData in Rails 3.2.8 application.
http://jsfiddle.net/RamPr/
$('.uploader input:file').on('change', function() {
$this = $(this);
$('.alert').remove();
$.each($this[0].files, function(key, file) {
$('.files').append('<li>' + file.name + '</li>');
data = new FormData();
data.append(file.name, file);
$.ajax({
url: $('.uploader').attr('action'),
contentType: 'multipart/form-data',
type: 'POST',
dataType: 'json',
data: data,
processData: false
});
});
});
But when I upload a file, I get this error in console:
webrick/server.rb:191:in `block in start_thread' ERROR ArgumentError: invalid %-encoding ("filename.jpeg" Content-Type: image/jpeg
How can I solve this error?

Have you seen this issue? Sending multipart/formdata with jQuery.ajax
It looks like you might be running into jQuery adding content-type headers, which causes the boundary string to be missing. From the above linked issue:
It’s imperative that you set the contentType option to false, forcing jQuery not to add a Content-Type header for you, otherwise, the boundary string will be missing from it. Also, you must leave the processData flag set to false, otherwise, jQuery will try to convert your FormData into a string, which will fail.
Based on that, give this a try:
$.ajax({
url: $('.uploader').attr('action'),
contentType: false,
cache: false,
processData: false,
type: 'POST',
dataType: 'json',
data: data
});
I haven't tried this myself, but I suspect this might be the droids you're looking for :)

Related

POST request done with Authenticity Token, but exception still rased

My controller is responding to a js GET request, and in my js.erb file I am reporting back with the Fingerprint2 generated browser data of the users browser. This is done with a POST request, because of the large data string, so I have inserted a beforeSend method that adds the Authenticity Token.
However, this is rejected with ActionController::InvalidAuthenticityToken - ActionController::InvalidAuthenticityToken. When I check, the header looks like it does in the GET requests that succeed:
X-CSRF-Token:hl/TgkY7k0yBG03KX9IBrsDhk2K4tUUh8JTooT7A0yYZ0l53p8lTt0F3dZvRwyS3bIkbbkuTdElP2KisozjXjw==
The js code looks like this:
(new Fingerprint2).get(function(fingerprint, components) {
return $.ajax({
url: "/user_browser",
type: "post",
beforeSend: function(xhr) {
xhr.setRequestHeader('X-CSRF-Token',
$('meta[name="csrf-token"]').attr('content'))
},
data: {
some_id: '123',
components: JSON.stringify(components),
fingerprint: fingerprint
},
dataType: "json"
}).success(function(data) {});
});
I found the root of the problem. Some days ago I changed my config/session_store.rb from:
MyApp::Application.config.session_store :cookie_store, key: '_my-app_session'
to:
MyApp::Application.config.session_store :disabled
When I changed this back the problem disappeared.

How to POST JSON data in body with Jenkins http-request plugin and Pipeline?

With v1.8.10 of the http-request plugin for Jenkins (I'm running 1.643), there is now support for POSTing a body in the request -- so this thread does not apply. I am wondering how to use this functionality in a Pipeline (v2.1) Groovy script? The Snippet Generator does not include this new field, so I have no example to build off of.
I have tried various ways to get the JSON data into the request body, but my Tomcat server always returns http 400 status code: The request sent by the client was syntactically incorrect.
Things I have tried:
def toJson = {
input ->
groovy.json.JsonOutput.toJson(input)
}
def body = [
displayName: [
text: "smoke test"],
description: [
text: "for smoke testing"],
genusTypeId: "type"
]
response = httpRequest consoleLogResponseBody: true, contentType: 'APPLICATION_JSON', httpMode: 'POST', requestBody: toJson(body), url: "https://${host}", validResponseCodes: '200'
def body = [
displayName: [
text: "smoke test"],
description: [
text: "for smoke testing"],
genusTypeId: "type"
]
response = httpRequest consoleLogResponseBody: true, contentType: 'APPLICATION_JSON', httpMode: 'POST', requestBody: body, url: "https://${host}", validResponseCodes: '200'
response = httpRequest consoleLogResponseBody: true, contentType: 'APPLICATION_JSON', httpMode: 'POST', requestBody: "{\"displayName\":{\"text\":"smoke test\"},\"description\":{\"text\":\"for smoke testing\"}, \"genusTypeId\":\"type\"}", url: "https://${host}", validResponseCodes: '200'
response = httpRequest consoleLogResponseBody: true, contentType: 'APPLICATION_JSON', httpMode: 'POST', requestBody: "'{\"displayName\":{\"text\":"smoke test\"},\"description\":{\"text\":\"for smoke testing\"}, \"genusTypeId\":\"type\"'}", url: "https://${host}", validResponseCodes: '200'
Scanning the http-request library code, it seems like setting this flag should work. I don't know how Pipeline plugins / Jenkins plugins work, so I wonder if the Pipeline -> http-request code accounts for this new parameter? Can someone point me to how I can make POSTs with request bodies work with the Pipeline, or where I need to modify Pipline plugin code to make the connection?
I think this is a bug. I added https://issues.jenkins-ci.org/browse/JENKINS-36203
and the PR: https://github.com/jenkinsci/http-request-plugin/pull/15

jQuery autocomplete runs every pageLoad

I am using jQuerys autocomplete. When page is load below ajax run automaticly. But i want to do this if anyone keydown this textbox. How can i change ?
$('#txtFirmaAdlari').autocomplete({
source: function (request, response) {
$.ajax({
url: '/Fatura/GetFirma/',
dataType: "json",
cache: false,
traditional: true,

Ajax Request Error when application Deployed to IIS7

I've deployed my MVC project application to IIS 7, and it seems to work fine till I execute an ajax request with the following format:
$.ajax({
type: 'POST',
url: "/ControllerName/ActionMethodName",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: dataToSend,
success: function (data) {
//Do Something
}
});
Then It eliminates the application name assigned by IIS and directly access the contoller/actionMethod path from the host!
Can anyone help me solve this?
Thanks

Asp.net MVC Controller Action string parameter doesn't get passed

In my controller I have
public JsonResult GetInfo(string id)
in my js
$.ajax({
contentType: 'application/json, charset=utf-8',
type: "POST",
url: "/Incidents/GetInfo",
data: { id: "777" },
cache: false,
dataType: "json",
success: function (response) {
//etc....
jquery ajax error delegate gets executed. If I use
data: { "777" },
no error, but the value doesn't get passed. This should be easy but I am beating my head against the wall. Maybe I am not allowed to pass strings to controller's actions?
What am I doing wrong here?
You are indicating application/json request and you are sending a application/x-www-form-urlencoded request. So you will have to choose between one of the two ways to encode parameters and not mix them.
application/x-www-form-urlencoded:
$.ajax({
type: "POST",
url: "/Incidents/GetInfo",
data: { id: "777" },
cache: false,
dataType: "json",
...
});
application/json:
$.ajax({
type: "POST",
url: "/Incidents/GetInfo",
contentType: 'application/json, charset=utf-8',
data: JSON.stringify({ id: "777" }),
cache: false,
dataType: "json",
...
});
The JSON.stringify method is natively built into modern browsers and is used to convert the javascript literal into a JSON string which is what we indicated that we are going to send the request as. If you are having to support legacy browsers you could include the json2.js script to your page which contains this method.
As a side note the dataType: "json" setting is not needed since the server will set the proper Content-Type header to application/json and jQuery is smart enough to use that.
And as a second side note you really don't want to be hardcoding an url like this in your javascript file: url: "/Incidents/GetInfo". What you want is to use url helpers when generating urls: url: "#Url.Action("GetInfo", "Incidents")".
Are you missing HttpPost attribute in your action? If not, use something like firebug or chrome dev tools to see http request/response and get more details...
[HttpPost]
public JsonResult GetInfo(string id)

Resources