File upload fails if I use camera to upload a picture - javascript

When I am trying to upload a picture from the existing files it is working without any issues. But when I choose a file directly by clicking from the camera from mobile it fails showing "CORS Error". I added "Access-Control-Allow-Origin" and I removed it none of them helps.
userData.getRequestCallbackWithPrescription = (req, result) => {
var data = new FormData();
data.append("call_request[call_time]", req.call_time);
req.image_upload.forEach((obj, i) => {
data.append(`prescription_upload[image_upload][${i}][image]`, obj.file, obj.file.name)
})
return $http({
method: "POST",
url: globalUrl + '/api/' + apiVersion + '/customer/web/call_requests',
headers: {
"Access-Control-Allow-Origin": "*",
'Content-Type': undefined,
"X-Auth-Token": $rootScope.UserDetails.Auth,
},
data
})
.then(function (response) {
return result(response.data);
}, function (response) {
return result(response);
});
}
Please help me with finding the solution.

I just compressed the image and uploaded it. It works!

Related

Streaming Chunk json data from POST request

I have a scenario that I need to upload an zip file.
In the zip file, there are lots of image files which will upload to AWS S3.
Because of the large amount of files in that zipfile, I want to get the information of upload process. In my opinion, the way I can get information is by using streaming response. Once server uploaded a file, respon a json to client.
Every time I upload a image to S3, I want to response a json object like the example bellow.
example for json streaming response:
{
"file_name": "imgae1.jpg",
"s3_url": "http://s3.url/key/to/file",
"other_key": "key for this uploaded file"
}
I'm trying to achieve this approach by using vue(cdn version) + axios(cdn version).
The code bellow which is how I upload my zip file.
function upload() {
var file = document.querySelector("#upload_file")
if (file.files.length <= 0) return
var formData = new FormData();
formData.append("file", file.files[0]);
formData.append("form_data", "form_data");
axios({
method: 'post',
url: "http://127.0.0.1:8000/",
headers: {
'Content-Type': 'multipart/form-data'
},
responseType: 'stream',
data: formData
}).then(function (response) {
if (response.status >= 200 && response.status < 300) {
alert("All images uploaded!")
}
})
}
but those examples I found are using axios npm package which I can't use.
Is there any recommend method or any resources that I can search?
Thanks for helping!
You can try using fetch instead like this:
fetch("http://example.url", {
method: "POST",
body: formData,
mode: "no-cors",
header: {
"Content-Type": "multipart/form-data",
},
}).then((response) => {
a = response.clone();
a.json().then((data) => {
//console.log('data', data)
});
});

Phonegap: Is there a way to get JSON data from an external url?

Actually am kinda disappointed as I tried many things and checked out many articles but non worked out for me.
function demo() {
console.log("Booooooooooooommmmmmmmmmm");
tokenV = document.getElementById("tokenString").value;
var urlF = "https://***********.com/connect/api.php?action=2&token="+tokenV;
const myHeaders = new Headers();
const myRequest = new Request(urlF, {
method: 'GET',
headers: myHeaders,
mode: 'cors',
cache: 'default',
});
fetch(myRequest)
.then(response => response.json())
.then(data => console.log(data));
}
I have already whitlist the domain inside my config file, am using phonegap CL latest version. I'm trying to connect to an api which will out put json.encode data if token were right.
Error output:
(index):50 Fetch failed loading: GET https://*******.com/connect/api.php.............
Another way I tried using cordova fetch plugin still failed:
function demo() {
console.log("Booooooooooooommmmmmmmmmm");
tokenV = document.getElementById("tokenString").value;
var urlF = "https://*********.com/api.php?action=2&token="+tokenV;
console.log("nowww1");
cordovaFetch(urlF, {
method : 'GET',
headers: {
'User-Agent': 'CordovaFetch 1.0.0'
},
})
.then(function(response) {
return response.json();
}).then(function(json) {
console.log('parsed json', json);
}).catch(function(ex) {
console.log('parsing failed', ex);
});
}
Error out put:
Error: exec proxy not found for :: FetchPlugin :: fetch (index):118 parsing failed TypeError: Network request failed
I can change the out put as I want but show me away to get the data from an external server???
Thank you

How to convert a file-path URI to a readable https URL

Is there a way to convert a captured file path uri as such
file:///var/mobile/Containers/Data/Application/1E1E919E-6C21-4CC7-B9C2-5B4B3BC84B0F/Library/Caches/ExponentExperienceData/%2540chuks93%252Fihu-main/Camera/F3B8EBCC-BB09-4603-AF7E-FD3CA792C237.jpg to say a temporary https URL?
Im working with the Microsoft azure face API and I'm running into errors that suggest that only way to run the API is with network URLs like https.
Anyone know of a workaround solution for this?
export default {
processImage: (image) => {
// Replace the subscriptionKey string value with your valid subscription key.
var subscriptionKey = "********************";
var uriBase = "https://westus.api.cognitive.microsoft.com/face/v1.0/detect?returnFaceId=true&returnFaceLandmarks=false&returnFaceAttributes=age,gender,headPose,smile,facialHair,glasses,emotion,hair,makeup,occlusion,accessories,blur,exposure,noise";
// Display the image.
var sourceImageUrl = image;
console.log(typeof sourceImageUrl)
console.log("here", sourceImageUrl);
// Perform the REST API call.
return fetch(uriBase, {
method: 'POST',
headers: {
"Content-type": "application/json",
"Ocp-Apim-Subscription-Key": subscriptionKey
},
body: JSON.stringify({ uri: sourceImageUrl })
})
.then((data) => data.json())
.then(function (data){
console.log("hello", data);
})
.catch(function (error) {
console.log(error);
});
}
}

Cannot get images to upload to wp/v2/media with React Native

I've been all over here and https://github.com/WP-API/WP-API/ and https://wordpress.org/ and cannot find anyone talking about this. I can get it working using postman and selecting the file, however i cannot get it work submitting it as either "multipart/form" or "image/png".
I also cannot find anything detailing exactly how the request should look. I can create attachments but they're empty images of the correct size using base64 data as the post body. I feel like I'm missing something simple but cannot figure out what it is. I'm using postman to abstract out other distractions, my headers are:
POST /wp-json/wp/v2/media
Content-Type: image/png
Content-Disposition: attachment;filename=image_1.png
Cache-Control: no-cache
Authorization: Bearer {JWT_Auth_token}
body is just
{
data:image/png;base64,{base64_string_here}
}
I get a returned response like it created an attachment, but when I check in the wp admin it's an blank file, that appears to be the correct kb size but doesn't display. What am I missing???
Finally figured it out! With the help of this WP Trac issue https://core.trac.wordpress.org/ticket/41774.
So my request looks like this now:
async function uploadImageAsync(urlbase, uri, base64, token) {
let apiUrl = urlbase + '/wp-json/wp/v2/media';
let formData = new FormData();
//dynamically get file type
let uriParts = uri.split('.');
let fileType = uriParts[uriParts.length - 1];
//generate some random number for the filename
var randNumber1 = Math.floor(Math.random() * 100);
var randNumber2 = Math.floor(Math.random() * 100);
formData.append('file', {
base64,
name: `photo-${randNumber1}-${randNumber2}.${fileType}`,
type: `image/${fileType}`,
});
let options = {
method: 'POST',
body: formData,
headers: {
Accept: 'application/json',
'Authorization' : 'Bearer ' + token,
'Content-Type': 'multipart/form-data',
'Cache-Control' : 'no-cache',
},
};
console.log('header options: ',options);
console.log('form-data options: ',formData);
return fetch(apiUrl, options);
}
When base64 comes in it's formatted simply as base64: {base64-string}. Not data:image/type, since that is specified in the form data. The other thing that's key here is setting the key of form to 'file'.
The original answer did not work for me, so I changed "uri: base64,". now it's working fine
formData.append('file', {
uri: base64,
name: `photo-${randNumber1}-${randNumber2}.${fileType}`,
type: `image/${fileType}`,
});
I wanted to put my solution somewhere in case other people find it useful. I am using react-native and redux, this solution is an action within the redux framework.
export const uploadMedia = image => {
return async function(dispatch, getState) {
const { token } = getState();
const uriParts = image.uri.split('.');
const fileType = uriParts[uriParts.length - 1];
const bodyFormData = new FormData();
bodyFormData.append('file', {
base64: image.base64,
name: `photo-qa.${fileType}`,
type: `image/${fileType}`
});
try {
const request = await fetch(
'http://stagingsite.test/wp-json/wp/v2/media',
{
method: 'POST',
headers: {
Accept: 'application/json',
Authorization: `Bearer ${token}`,
'Content-Type': 'multipart/form-data; boundary=__boundrytext__'
},
body: bodyFormData
}
);
const response = await request.json();
console.log({
text: 'uploadMedia', response, request
});
} catch (error) {
return ErrorHandler(error);
}
};
};

React Native - Fetch POST not working

I am having huge troubles getting my fetch POST calls to work on iOS. My standard Fetch calls work and the Fetch POST calls work fine on android but not iOS.
The error that comes up is "Possible Unhandled Promise Rejection (id: 0): Unexpected token < in JSON at position 0"
It actually saves the post data to my server but throws that error.
I tried debugging the network request using GLOBAL.XMLHttpRequest = GLOBAL.originalXMLHttpRequest || GLOBAL.XMLHttpRequest; before the API call coupled with using CORS in my chrome debug tools. From there I can see that it is making two post calls one after the other. The first one has type "OPTIONS" while the second one has type "POST". It should probably be noted that the call works in the App while using CORS and the line of code above.
I'm very confused and have exhausted all avenues.
My code im using for refrence is as follows.
return fetch(url,{
method: 'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
}).then((res) => res.json());
If JSON.stringify is not working, then try to use FormData.
import FormData from 'FormData';
var formData = new FormData();
formData.append('key1', 'value');
formData.append('key2', 'value');
let postData = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data'
},
body: formData
}
fetch(api_url, postData)
.then((response) => response.json())
.then((responseJson) => { console.log('response:', responseJson); })
.catch((error) => { console.error(error); });
You use the following code for POST request in react native easily. You need to only
replace the parameter name and value and your URL only.
var details = {
'userName': 'test#gmail.com',
'password': 'Password!',
'grant_type': 'password'
};
var formBody = [];
for (var property in details) {
var encodedKey = encodeURIComponent(property);
var encodedValue = encodeURIComponent(details[property]);
formBody.push(encodedKey + "=" + encodedValue);
}
formBody = formBody.join("&");
fetch('http://identity.azurewebsites.net' + '/token', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded'
},
body: formBody
}).
.then((response) => response.json())
.then((responseData) => {
console.log("Response:",responseData);
}).catch((error) => {
Alert.alert('problem while adding data');
})
.done();
I would guess the response you are receiving is in HTML. Try:
console.warn(xhr.responseText)
Then look at the response.
Also, IOS requires HTTPS.
Edit: Possible duplicate: "SyntaxError: Unexpected token < in JSON at position 0" in React App
Here is an example with date that works for me!
The trick was the "=" equal and "&" sign and has to be in a string format in the body object.
Find a way to create that string and pass it to the body.
====================================
fetch('/auth/newdate/', {
method: 'POST',
mode: 'cors',
redirect: 'follow',
body: "start="+start.toLocaleString()+"&end="+end.toLocaleString()+"",
headers: new Headers({
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"
})
}).then(function(response) {
/* handle response */
if(response.ok) {
response.json().then(function(json) {
let releasedate = json;
//sucess do something with places
console.log(releasedate);
});
} else {
console.log('Network failed with response ' + response.status + ': ' + response.statusText);
}
}).catch(function(resp){ console.log(resp) });
server node.js?
npm i cors --save
var cors = require('cors');
app.use(cors());
res.header("Access-Control-Allow-Origin: *");

Categories

Resources