Grails upload files with angular - javascript

i have an angular ui and grails as end points, i posted the files it went ok, but grails seems can't read it.
my angular codes
function sendComment(comment, cb, cbError,token) {
//var promise = $q.defer();
var formData = new FormData();
formData.append('email', comment.email);
formData.append('PNR', comment.PNR);
formData.append('content', comment.content);
formData.append('commentFile',file);
var req = {
method: 'POST',
url: ENV.baseurl +"api/addComment",
transformRequest: angular.identity,
headers: {
'Accept': "application/json",
'Content-Type': undefined,
'Authorization': 'Bearer '+token,
},
data:formData,
}
$http(req).success(cb).error(cbError);
}
my chrome log is
my grails end point
def addComment() {
Comment comment =new Comment()
JSONObject respond = new JSONObject()
comment.content = params.content
comment.PNR = params.PNR
comment.email = params.email
def file = request.getFile('commentFile')
comment.person = Person.findByEmail(params.email);
print file
if (comment.save(flush: true)) {
if (!file) {
CommentFiles files = new CommentFiles()
files.files = new File(file)
files.contentType = uploadedFile.contentType
files.comment = comment
files.save(flush: true)
}
respond.error = false;
respond.message = "comment saved";
response.status = 201;
} else {
print comment.errors.allErrors
respond.error = true;
respond.message = "Could not save comment";
response.status = 409;
}
}
the endpoint have a CORS Interceptor in it, but i'm not 100% sure
please help thanks!

Try without transformRequest: angular.identity,
thanks James Kleeh

Related

How to display image data returned from dreambooth / stable-diffusion model?

I'm querying a dreambooth model from Hugging Face using the inference API and am getting a huge data response string back which starts with: ����çx00çx10JFIFçx00çx01çx01çx00çx00çx01çx0...
Content-type is: image/jpeg
How do I decode this and display it as an image in javascript?
Not 100% sure but I suppose something similar to that should do it.
for (var e = atob("����çx00çx10JFIFçx00çx01çx01çx00çx00çx01çx0..."), t = new Array(e.length), r = 0; r < e.length; r++) t[r] = e.charCodeAt(r);
var n = new Uint8Array(t),
a = new Blob([n], {
type: "image/jpeg"
}),
x = (window.URL || window.webkitURL).createObjectURL(a);
let img = document.createElement("img")
img.src = x;
got it working by including a responseType param in the axios request.
Node.js code:
const inputData = {
inputs: prompt,
options: {
wait_for_model: true,
},
}
const response = await axios({
url: `https://api-inference.huggingface.co/models/${model}`,
method: 'POST',
headers: {
Authorization: `Bearer ${process.env.HUGGING_FACE_TOKEN}`,
Accept: 'application/json',
'Content-Type': 'application/json',
},
data: JSON.stringify(inputData),
responseType: 'arraybuffer',
})
const mimeType = response.headers['content-type']
const result = response.data
const base64data = Buffer.from(result).toString('base64')
const img = `data:${mimeType};base64,` + base64data
return img
React code:
<img src={img} />

How to upload an image to ImgBB API using Javascript in a firefox addon

Info on the API can be found here. It does not give any details for using with Javascript, only with curl.
Have tried numerous different methods from old posts on here but this is the closest I have got so far.
function main() {
var ul = document.querySelector('.redactor_toolbar')
if(ul != null)
{
var new_li = document.createElement('li')
var new_a = document.createElement('a')
new_li.appendChild(new_a)
ul.appendChild(new_li)
new_a.addEventListener('click', function() {
var input = document.createElement('input');
input.type = 'file';
input.onchange = e => {
uploadImage(e.target.files[0])
}
input.click();
})
}
}
async function uploadImage(img)
{
var form = new FormData();
form.append('image', img)
var url = 'https://api.imgbb.com/1/upload?key=8d5867a9512390fb5e5dc97839aa36f6'
const config = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Access-Control-Allow-Origin': '*',
'Connection': 'keep-alive',
'Content-Type': 'application/json',
},
body: form
}
const response = await fetch(url, config)
const json = await response.json()
console.log(response)
}
The JSON response:
is the same problem for mi application.
Create
<input type="file" id="input_img" onchange="fileChange()" accept="image/*">
The code javascript
function fileChange(){
var file = document.getElementById('input_img');
var form = new FormData();
form.append("image", file.files[0])
var settings = {
"url": "https://api.imgbb.com/1/upload?key=8d5867a9512390fb5e5dc97839aa36f6",
"method": "POST",
"timeout": 0,
"processData": false,
"mimeType": "multipart/form-data",
"contentType": false,
"data": form
};
$.ajax(settings).done(function (response) {
console.log(response);
var jx = JSON.parse(response);
console.log(jx.data.url);
});
}
This work for me

$http.get doesn't have all headers

I'm trying to download a file from my web-api controller. I succeded until I wanted to get the custom header of the response.
web-api controller
[HttpGet]
[Route("vorlage")]
[ResponseType(typeof(object))]
[SwaggerResponse(HttpStatusCode.OK, Type = typeof(object))]
public HttpResponseMessage DownloadVorlage()
{
HttpResponseMessage result = Request.CreateResponse(HttpStatusCode.OK);
result.Content = new ByteArrayContent(Properties.Resources.Vorlage_Batch);
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
result.Content.Headers.ContentDisposition.FileName = "original name.xlsx";
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
result.Headers.Add("X-Filename", "original name.xlsx");
return result;
}
angularjs code
function DownloadVorlage($scope, $http, WebApiBaseUri) {
var request = {
method: 'GET',
url: WebApiBaseUri + 'batchmode/vorlage',
responseType: 'arraybuffer',
headers: {
'Accept': 'application/json;odata=verbose'
}
};
$http(request).then(function (response) {
var headers = response.headers();
var filename = headers['X-Filename'] || 'replacement name.xlsx';
var contentType = headers['content-type'] || 'application/octet-stream';
download(response.data, filename, contentType);
}, function (response) {
console.log(response);
});
}
The content is in the right type and it is possible to save the file.
When I test the API with postman I got all headerinformation that I need.
But all header information I go are:
cache-control: "no-cache"
content-type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
expires: "-1"
pragma: "no-cache"
I'm missing the "X-Filename" information and have no clue how to get it.

Using JavaScript Fetch with Formidablejs, Expressjs

I'm using Reactjs saga to send a post request using fetch. Also I'm trying to use formidable instead of usual body-parser. I'm getting weird parsing issues. What am I doing wrong?
// saga simplified piece of code
const { loginEmail, loginPwd } = request.payload;
let postLoginSubmitOptions = {
method: "POST",
headers: {
'Accept': 'application/json, application/xml, text/plain, text/html, *.*',
'Content-Type' : 'application/x-www-form-urlencoded'
},
body: JSON.stringify({
loginEmail: loginEmail,
loginPwd: loginPwd
})
};
const response = yield call(fetch, `http://www.example.com/register`, postLoginSubmitOptions);
// expressjs side, simplified view
router.post('/register', function(req, res, next) {
console.log('registering user');
var form = new formidable.IncomingForm();
form.parse(req, function(err, fields, files) {
if(err){
console.log(err);
}
console.log(`incoming fields via form parse`);
console.log(fields); // { '{"loginEmail":"my-email#gmail.com","loginPwd":"my-password"}': '' }
console.log(fields.loginEmail); // undefined
});
}
pass content type as json
let postLoginSubmitOptions = {
method: "POST",
headers: new Headers({'content-type': 'application/json'}),
body: JSON.stringify({
loginEmail: loginEmail,
loginPwd: loginPwd
})
};
I don't know where exactly the problem was but tried encoding data differently and then it worked. Getting a nice parsed object now with formidable: { loginEmail: 'dan#dan.com', loginPwd: 'asjdfkjsadlf' }
function sendData(data) {
const { loginEmail, loginPwd } = request.payload;
const body = { loginEmail, loginPwd };
var urlEncodedData = "";
var urlEncodedDataPairs = [];
var name;
for(name in body) {
urlEncodedDataPairs.push(encodeURIComponent(name) + '=' + encodeURIComponent(body[name]));
}
urlEncodedData = urlEncodedDataPairs.join('&').replace(/%20/g, '+');
var httpHeaders = {
'Content-Type' : 'application/x-www-form-urlencoded',
'Accept' : 'application/json'
}
let postOptions = {
method: 'post',
headers: new Headers(httpHeaders),
/*mode: 'no-cors',*/
body: urlEncodedData
};
try {
const response = yield call(fetch, `http://www.example.com/register`, postOptions);
const data = yield call([response, response.json]);
console.log(`data returned by fetch`);
console.log(data);
yield put({type: 'LOGIN_SUBMIT_RESPONSE', payload: data.message})
} catch (e) {
console.log(`error fetch post object`);
}
}
Thanks everyone!

How can I make my .factory return the result on a promise (.then)

I have this factory:
I'm basically trying to get a file to my server. And when I finish uploading it, I want it to return an answer.
.factory('fileUpload', function($http)
{
var ofileUpload = {};
ofileUpload.uploadFileToUrl = function(file, uploadUrl)
{
var fd = new FormData();
fd.append('file', file);
return $http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
,function(){
ofileUpload.answer="success";
ofileUpload.respuesta;
},function(){
ofileUpload.answer="failure";
ofileUpload.answer;
};
}
return ofileUpload;
})
In my controller I am trying to do this:
//I am executting this:
fileUpload.uploadFileToUrl(file, uploadUrl).then(function(){
console.log(fileUpload.answer)
});
but this error appears to me.
TypeError: fileUpload.uploadFileToUrl(...).then is not a function
How can I have my .factory return the response on a promise to receive the value returned (ofileUpload.answer) in my controller?
I solved that. thank you!
.factory('fileUpload', function($http)
{
var ofileUpload = {};
ofileUpload.uploadFileToUrl = function(file, uploadUrl)
{
var fd = new FormData();
fd.append('file', file);
return $http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
}).then(function(data) {
ofileUpload.answer="success";
},function(response) {
ofileUpload.answer="failure";
});
}
return ofileUpload;
})

Categories

Resources