I have a problem with the PDF file I get from the API in response to a Json GET request.
It does get a good string in Json, however, which makes the PDF file that appears corrupted. I tried to convert the response to a string but it didn't do anything.
Here is my code:
getPDF() {
axios
.get(apiurl + "api/Dok", { params: { }, headers: { } })
.then(response => {
const res = response.data.fileData;
const pdfcode = res.toString();
this.convertPDF(pdfcode)
}
)
.catch(error => {
alert('error')
});
}
convertPDF(value) {
const file = new Blob(
[value],
{type: 'application/pdf'});
const fileURL = URL.createObjectURL(file);
window.open(fileURL);
}
So if i'm import the pdf file from local and add it to this function istead of url in console i'm getting long string response
JVBERi0xLjUNCjQgMCBvYmoNCjw8L1R5cGUgL1BhZ2UvUGFyZW50IDMgMCBSL0NvbnRlbnRzIDUgMCBSL01lZGlhQ...
and PDF works, but when get it from URL i'm getting :
{"fileData":"JVBERi0xLjUNCjQgMCBvYmoNCjw8L1R5cGUgL1BhZ2UvUGFyZW50...
I checked it in notepad, the first answer and the content of "" are identical
any ideas what i can do?
Related
I am trying to post a file into API my file is shown in the console, but in API payloads it is showing [object file] on uploading.
This is a function for taking file
handleFileChange = (e) => {
const files = e.target.files[0];
this.setState({ document: files });
console.log("Guru4666", this.state.document);
};
The state is then pushed into an object called award value.
SubmitAward() {
var awardValue = {
title: this.state.awardTitle,
award_img: this.state.document,
};
console.log("awardValue", awardValue);
this.state.awarddata.push(awardValue);
}
Then the API is called.
instructor_register() {
var titlearr = [];
var awardimgarr= [];
const UserToken = localStorage.getItem("UserToken");
this.state.awarddata.map((Data) => {
console.log("AwardDataa", Data);
titlearr.push(Data.title);
awardimgarr.push(Data.award_img);
});
const formdata = new FormData();
formdata.append("first_name",this.state.firstname)
formdata.append("instructor_award_name",titlearr)
formdata.append("instructor_award_img",awardimgarr)
axios({
method: "post",
url: `${API_AUTH_URL}instructor-register`,
data: formdata,
headers: { Authorization: "Bearer" + UserToken },
})
.then((response) => {
//this.setState({ modalVisibleLoader: false })
console.log("response.....", response.data);
}
Payload is
instructor_award_img: [object File]
You are attempting to append an array to the formdata object. This isn't a supported data type, so it gets converted to a string.
Supported data types are strings and blobs (files are a type of blob).
Append the file instead.
If you want to append multiple files, do it by looping over the array and appending each file in turn.
I feel like I'm going crazy, I really hope this is not a duplication although I did find multiple similar issues but none of the solutions worked for me.
I'm using react-signature-canvas to let people sign on the website. That library offers a toDataURL() method, which turns the canvas into a base64 string. I then remove the "data:image/png;base64," from that string and turn it into a Blop using the fetch function. Getting a presigned URL I use axios.put() to send the image to an S3 bucket. However when I download that image from that bucket I can't open it because it's corrupted. When I put the dataURL into a base64 to image converter online the string works.
Here is my code so far:
const fileUpload = async signatureImageSrc => {
const signatureImage = await (await fetch(signatureImageSrc)).blob();
const fileBody = new FormData();
fileBody.append("signature", signatureImage);
const config = {
headers: {
"Content-Type": "application/json"
}
};
const fileName = id + "-" + "signature.png";
axios
.post("/upload_url", {fileName: fileName, fileType: "image/png"}, config)
.then(res => {
axios.put(res.data, fileBody, config).then(res => console.log(res));
});
};
I have tried changing the type of the blop (because it currently set to text/html) as well as sending it appended to a Form data object, as well as changing the Content-Type in the config object. I tried creating it as a file ( new File([blop], fileName)) and sending it through and more.
It always gets corrupted or sometimes it's a .json or .html file.
I finally got it to work.
I used a function to create a blob from the base64 string and then turned that blob into a file by adding the lastModifiedDate and name property to it.
Additionally I did not use a form data element anymore but instead uploaded that created file directly to the S3 bucket.
The code looks like this now:
const fileUpload = signatureImageSrc => {
const config = {
headers: {
"Content-Type": "application/json"
}
};
const configBlop = {
headers: {
"Content-Type": "multipart/form-data"
}
};
const blob = b64toBlob(signatureImageSrc, "image/png");
const fileName = id + "-" + "beauftragung-unterschrift.png";
const file = blobToFile(blob, fileName);
axios
.post("/upload_url", {fileName: fileName, fileType: "image/png"}, config)
.then(res => {
axios.put(res.data, file, configBlop).then(res => console.log(res));
});
};
The function to create the Blob is taken from here and the blobToFile function looks like this:
const blobToFile = (theBlob, fileName) => {
theBlob.lastModifiedDate = new Date();
theBlob.name = fileName;
return theBlob;
};
I am currently working in angular 6. i have to download pdf file from bytearray.
when i tried to download an pdf file. it downloads but when i open it. it shows error. please help me with it.
In the download.component.ts i am getting response as two values. first pdfname, second pdfbytearray. i am getting those values from component response.
sample response:
{
pdfName: "test.pdf",
pdfByteArray: "JVBERi0xLjQKJeLjz9MKMSAwIG9iago8PC9Qcm9kdWNlcij"
}
download.service.ts:
generatePdf(id) {
const httpOptions = {
'responseType': 'arraybuffer' as 'json'
};
return this.http.post<any>(URL.BASE_URL + 'application/generate?id='+ id,
{ httpOptions },
);
}
download.component.ts:
import { saveAs } from 'file-saver/FileSaver';
generatePdf() {
this.downloadApiService.generatePdf('4')
.subscribe( pdf => {
console.log('pdf response: ', pdf);
var mediaType = 'application/pdf';
var blob = new Blob([pdf.pdfByteArray], {type: mediaType});
let fileName = pdf.pdfName;
saveAs(blob, fileName);
}, err => {
console.log('Pdf generated err: ', JSON.stringify(err));
});
}
Receiving HTTP Failure during parsing in Angular. Goal is to download a csv file from the api response
Controller:
downloadFile(data) {
const blob = new Blob([data], { type: 'text/csv' });
const url = window.URL.createObjectURL(blob);
window.open(url);
}
getFileDownload(): void {
this.iportalUploadService.getFileDownload(this.fileName).subscribe(data => {
debugger;
this.fileDownload = data;
this.downloadFile(data);
});
}
Service:
private fileDownloadUrl = 'file-transfer/validationErrorsCSV';
formHtppOptions(params): any {
const httpOptions = {
headers: { 'Application-Token': this.getToken() },
params: params,
};
return httpOptions;
}
getFileDownload(fileName): Observable < Object > {
const baseUrl = this.getBaseUrl();
return this.http.get<Object>(baseUrl + this.fileDownloadUrl, this.formHtppOptions({ fileName: fileName }));
}
Below is the console error I am receiving
console error
Response format Photo
Response photo
You are getting this error because your response is not in JSON format. You are trying to convert it into an object and CSV text cannot be parsed to a proper json object. Here is what you might want to do:
getFileDownload(fileName): Observable<any> {
const baseUrl = this.getBaseUrl();
return this.http.get(baseUrl + this.fileDownloadUrl, this.formHtppOptions({fileName: fileName})).pipe(map((data:any) => this.converter.ToJson(data)));
}
Usually, I have a "converter" service that does this kind of parsing. You can make use of papa parse, or parse yourself by looping through the response.
Update: Here is an example of manually parsing the response: http://blog.sodhanalibrary.com/2016/10/read-csv-data-using-angular-2.html
Have a look at the above blog post.
I resolved this issue by adding responseType: 'text' in formhttpOtions.
I’m using Expo’s image picker and I’m getting this output:
Object {
"cancelled": false,
"height": 468,
"uri": "file:///data/user/0/host.exp.exponent/cache/ExperienceData/%2540jbaek7023%252Fstylee/ImagePicker/9a12f0a3-9260-416c-98a6-51911c91ddf4.jpg",
"width": 468,
}
I could render my image, but I just realized that the URL is the phone’s local URI.
I’m using Redux-Thunk and Axios to send HTTP POST request:
export const sendPost = ( imageUri, title, content ) => async dispatch => {
let response = await axios.post(`${ROOT_URL}/rest-auth/registration/`, {
image, <<<<- I can't put image uri here :( it's LOCAL path
title,
content
})
if(response.data) {
dispatch({ type: POST_CREATE_SUCCESS, payload: response.data.token })
} else {
dispatch({ type: POST_CREATE_FAIL })
}
}
UPDATE I changed a request call
let headers = { 'Authorization': `JWT ${token}`};
if(hType==1) {
headers = { 'Authorization': `JWT ${token}`};
} else if (hType==2) {
headers = { 'Authorization': `Bearer ${token}`};
}
let imageData = new FormData();
imageData.append('file', { uri: image });
let response = await axios.post(`${ROOT_URL}/clothes/create/`, {
image: imageData,
text, bigType, onlyMe ...
}, {headers});
!! sorry for the complication but image variable name; image is uri for the image. I didn't want to change the name of original variable name
and on server, it's printing
'image': {'_parts': [['file', {'uri': 'file:///data/user/0/host.exp.exponent
/cache/ExperienceData/%2540jbaek7023%252Fstylee/
ImagePicker/78f7526a-1dfa-4fc9-b4d7-2362964ab10d.jpg'}]]}
I found that gzip compression is a way to send image data. Does it help?
Another option is to convert your image to base64 and send the string. Downsize is that usually the base64 strings has a bigger size than the image itself.
Something like this:
function readImage(url, callback) {
var request = new XMLHttpRequest();
request.onload = function() {
var file = new FileReader();
file.onloadend = function() {
callback(file.result);
}
file.readAsDataURL(request.response);
};
request.open('GET', url);
request.responseType = 'blob';
request.send();
}
It has to be a local URI, there's no issues with that, how else are you going to point to the image.
Now to upload the image you should first wrap it inside of FormData:
// add this just above the axios request
let img = new FormData();
img.append('file', { uri: imageUri });
Then inside of your axios request body add:
image: img,
EDIT: This question in it's current form is unanswerable.
I'm using the same Expo’s image picker with React-native in one of my projects as OP and everything works just fine, there's no issues with FormData.
After having talked with OP in a stackoverflow chat, couple of days ago, and stripping the request down to just an image, the server started throwing encoding errors:
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 168: invalid start byte
So the issue is with OP's Django backend not being setup correctly in parsing the image, and not with the sending of the image itself - which makes the question unanswerable.
you cant use react-native-fetch-blob .....
import RNFetchBlob from " react-native-fetch-blob"
PostRequest(PATH){
RNFetchBlob.fetch('POST', "[URL]", {
"x-session-id": "SESSION_ID", //or Custom headers
'Content-Type': 'multipart/form-data',
}, [
{ name: 'image', filename: 'vid.jpeg', data: RNFetchBlob.wrap(PATH) },
// custom content type
]).then((res) => {
console.log(res)
})
.catch((err) => {
console.log(err)
// error handling ..
})
}
}
for reference react-native-fetch-blob