File upload Http client issue Titanium - titanium

I am trying to upload a .mp4 file to some server. I am using the HTTP client provided by titanium. when I upload the file, HTTP client is adding some headers in the file due to which the file gets corrupted and cannot be played. When I download the uploaded file and open it in notepad I can see the header which are added to the file.
What should I do so that these headers are not added to the file?
Thanks a lot!
// CODE
var uploadFile = Titanium.Filesystem.getFile(dir, _previewUrl);
var fileUploadUrl = 'Some Url for the server to upload';
var headers = { 'Content-Type' : 'multipart/form-data' };
var content = { 'file' : uploadFile };
var xhr = Titanium.Network.createHTTPClient();
for(var key in _headers) {
xhr.setRequestHeader(key, _headers[key]);
}
xhr.onerror = function(e)
{
Ti.UI.createAlertDialog({title:'Error', message:e.error}).show();
Ti.API.info('IN ERROR ' + e.error);
};
xhr.setTimeout(20000);
xhr.onload = function(e)
{
Ti.UI.createAlertDialog({title:'Success', message:'status code ' + this.status}).show();
Ti.API.info('IN ONLOAD ' + this.status + ' readyState ' + this.readyState);
};
xhr.onsendstream = function(e)
{
ind.value = e.progress ;
Ti.API.info('ONSENDSTREAM - PROGRESS: ' + e.progress);
};
// open the client
xhr.open('POST',fileUploadUrl);
// send the data
xhr.send(content);
// END

try setting the headers after you call xhr.open
// open the client
xhr.open('POST',fileUploadUrl);
for(var key in _headers) {
xhr.setRequestHeader(key, _headers[key]);
}

Do not add { 'Content-Type' : 'multipart/form-data' }; header. This way you should get the file properly without any headers like boundary and file name etc. I could send image, 3gpp file like that successfully But, when I send a video file, my server PHP code $_FILES will be empty array. Even the $_FILES["files"]["error"] have no value. There should some other trick to send video file. (Titanium SDK 3.1.1 & android 4.1.2)
xhr.open("POST", URL);
xhr.send({
files : Titanium.Filesystem.getFile(Titanium.Filesystem.applicationDataDirectory, sourcefilename)
});
}

Try not sending the raw blob itself. Send base64 encoded string instead.
var uploadFile = Titanium.Filesystem.getFile(dir, _previewUrl);
var base64File = Ti.Utils.base64encode(uploadFile.read()).toString();
And try changing the header to
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(base64File);
That will solve your problem.

Related

Axios get : response with 403 error forbidden

I'm trying to use Open API in Vue.js.
When the webpage was created, i just wanna check the fetched data on console log.
This is the error image. enter image description here
And this is Network tab. enter image description here
code
created() {
const request = require("request");
const SERVIECE_KEY =" blah blah"; // secret
let url =
"https://cors-anywhere.herokuapp.com/http://openapi.molit.go.kr:8081/OpenAPI_ToolInstallPackage/service/rest/RTMSOBJSvc/getRTMSDataSvcAptTrade";
// use 'herokuapp' as a proxy server
let queryParams =
"?" +
encodeURIComponent("serviceKey") +
`=${SERVIECE_KEY}`;
queryParams +=
"&" +
encodeURIComponent("LAWD_CD") +
"=" +
encodeURIComponent("11110");
queryParams +=
"&" +
encodeURIComponent("DEAL_YMD") +
"=" +
encodeURIComponent("201512");
request(
{
url: url + queryParams,
method: "GET",
},
function (error, response, body) {
console.log("Status", response.statusCode);
console.log("Headers", JSON.stringify(response.headers));
console.log("Reponse received", body);
}
);
},
Try
The same request works on Postman with encoded service key (no proxy server URL).
it works on a browser as well.
Use decoded and encoded service key both above the code to check if the URL i entered is wrong
I know 403 error(forbidden) is due to the permission to access.
But i really don't know what could be the problem.

returning a PDF on the fly using NextJS 9

I'm trying to figure out how to send a pdf that was dynamically created to the client from the nextjs 9 api. I'm not sure if this is a nextjs error, a file pathing error or a webpack error. Guidance would be great.
filepath = /pages/api/pdf.js
var fs = require('fs')
export default function handle(req, res) {
console.log(req.body) // The request body
console.log(req.query) // The url querystring
console.log(req.cookies) // The passed cookies
var stream = fs.createReadStream(destinationPDF);
var filename = "filled.pdf";
// Be careful of special characters
filename = encodeURIComponent(filename);
// Ideally this should strip them
res.setHeader('Content-disposition', 'inline; filename="' + filename + '"');
res.setHeader('Content-type', 'application/pdf');
stream.pipe(res);
}
The error
Error: Failed to open PDF file:
../../public/static/85.pdf
resolves to localhost:3000/static/85.pdf
Error of concern:
let data = _babel_runtime_corejs2_core_js_object_assign__WEBPACK_IMPORTED_MODULE_0___default()(fdfData, fieldNames);
It's currently not possible to read files from API routes or pages.
https://github.com/zeit/next.js/pull/8334

Google app api with freshdesk api error

On using the freshdesk api from google app script getting an error
"{"code":"invalid_content_type","message":"Content-Type header is set to . It should be set to application/json"}"
The code used for this
function hd_getTickets(){//using v2
var API_KEY = 'xxxxxxxxxxxxxx';
var headers = {'Content-type': 'application/json','Authorization': 'Basic ' + Utilities.base64Encode(API_KEY + ':X') };
var data = { "query":"\"priority:3\"" };
var ENDPOINT = 'https://xxxxxxx.freshdesk.com/api/v2';
var url = ENDPOINT + '/search/tickets';
var options = { 'method': 'get', muteHttpExceptions: true,'headers': headers,'payload' : JSON.stringify(data)};
var response = UrlFetchApp.fetch(url, options);
}
Changing the endpoint and removing the payload from options work so assuming authorization and header is fine
var url = ENDPOINT + '/tickets';
var options = {'method':'get','headers':headers, muteHttpExceptions: true};
Using postman this works
https://xxxxxxx.freshdesk.com/api/v2/search/tickets?query="priority:3"
with header set as
Content-Type:application/json
Authorization:Basic xxxxxxxxxxxxxxxx
You are sending a GET request to the API with the Payload variable in the options.
In my opinion payloads are used for POST requests.
Construct the URL with the query parameters and send it without the Payload.
Example: 'https://domain.freshdesk.com/api/v2/search/tickets?query="priority:3"'
See details here: HTTP GET with request body
Freshdesk API Doc: https://developers.freshdesk.com/api/#filter_tickets
Two issues found
1) web site does not support payload based get.
2) google apps doesn't support special characters in url.
Adding parameters to the original url and encoding the double quotes works.
var ENDPOINT = 'https://xxxxxx.freshdesk.com/api/v2';
var query ='query='+encodeURIComponent("\"priority")+":1"+encodeURIComponent("\"");
var url = ENDPOINT + '/search/tickets?'+query;
var options = {'method': 'get', muteHttpExceptions: true,'headers': headers};
var response = UrlFetchApp.fetch(url, options);

Sending a file with XMLHttpRequest() to Tika server

I'm trying to send a PDF for content extraction to a Tika Server but always get the error: "Cannot convert text from stream using the source encoding"
This is how Tika is expecting the files:
"All services that take files use HTTP "PUT" requests. When "PUT" is used, the original file must be sent in request body without any additional encoding (do not use multipart/form-data or other containers)." Source https://wiki.apache.org/tika/TikaJAXRS#Services
What is the correct way of sendig the file with XMLHttpRequest()?
Code:
var response, error, file, blob, xhr;
file = new File("/PROJECT/web/dateien/ai/pdf.pdf");
blob = file.toBuffer().toBlob("application/pdf");
url = "http://localhost:9998/tika";
// send data
try {
xhr = new XMLHttpRequest();
xhr.open("PUT", url);
xhr.setRequestHeader("Accept", "text/plain");
xhr.send(blob);
} catch (e) {
error = e;
}
({
response: xhr.responseText,
status: xhr.statusText,
error: error,
type: xhr.responseType,
blob: blob
});
Error:
I suspect PUT request to be converted into a POST request by wakanda when there is blob in XHR body. Can you wireshark your XHR request and add details ? If so, you can probably fill an issue in wakanda (https://github.com/Wakanda/wakanda-issues/issues)
Hope it helps,
Yann

Angular JS file upload isn't processed properly by connect-multiparty

I have been tearing my hair out for the last couple of hours and I hope someone here could help me out. I have an angular application which is using (https://github.com/danialfarid/ng-file-upload) and no matter what I try I can't seem to be able to get the files out at the other end.
I do see the correct request payload in the Chrome developer tools:
------WebKitFormBoundaryEwG0XOfjS0IjwRji
Content-Disposition: form-data; name="file"; filename="images.png"
Content-Type: image/png
------WebKitFormBoundaryEwG0XOfjS0IjwRji-
My code on the server side looks as follows, I am using a router which is using connect-multiparty.
Router.js:
router.post('/api/v1/uploaddocument', multipartyMiddleware, UserFunctions.saveDocument);
The actual save document function:
saveDocument: function(req,res)
{
console.log(req.body, req.files, req.data, req.file)
}
The controller posting this message in angular is:
iSelectClient.controller('PageUploadDocumentCtrl', ['$scope', 'Upload', function ($scope, Upload) {
$scope.$watch('files', function () {
$scope.upload($scope.files);
});
$scope.upload = function (files) {
if (files && files.length) {
for (var i = 0; i < files.length; i++) {
var file = files[i];
Upload.upload({
url: 'http://localhost:3000/api/v1/uploaddocument',
fields: {'username': $scope.username},
file: file
}).progress(function (evt) {
var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
console.log('progress: ' + progressPercentage + '% ' + evt.config.file.name);
}).success(function (data, status, headers, config) {
console.log('file ' + config.file.name + 'uploaded. Response: ' + data);
});
}
}
};
}]);
I am not using app.use(bodyparser()) on the server side, for each individual route I am defining which parser to use.
What o what could it be?
EDIT
I had an interceptor on each call which set the application type to json, so it never reached the other end correctly. Fixed now, using the exact same setup as below
I had an interceptor on each call which set the application type to json, so it never reached the other end correctly. Fixed now, using the exact same setup as below