I am trying to send an image through a resource and recovery in a php file but I have not succeeded, this is my JS file:
//* AJAX *//
startAsyncNews: function(){
if(this.sendimage){
var formdata = new FormData();
formdata.append("file",this.contentnew.imageFile );
console.log(this.contentnew.imageFile);
}
// POST /someUrl
this.$http.post('controllers/newsController.php', {
data:{action : this.accion_new, data_new: this.contentnew , imgf : formdata}
}).then(response => {
}, response => {
console.log("error");
});
},
imageSelect: function($event){
this.sendimage=true;
this.contentnew.imageFile =$event.target.files[0];
}
When I use the console.log = console.log (this.contentnew.imageFile), it shows me the properties of the image correctly, that is, it is sending the file well, but when I receive it in php and I do vardump I get this object ( stdclass) # 3 (0) no properties no properties and with json_decode / encode I get it empty, also try
headers: {
'content-type': 'multipart/form-data'
}
But it generates the following error:
Missing boundary in multipart/form-data POST
You need to add all your data in formdata Object using formdata.append(key,value) function.
Then you simply send formdata
formdata.append('action ',this.accion_new);
formdata.append('data_new',this.contentnew);
this.$http.post('controllers/newsController.php', {
data:formdata
});
// or just if i'm not mistaken
this.$http.post('controllers/newsController.php',formdata);
object in http request data.
I don't know what this.accion_new and this.contentnew are, but this line:
this.$http.post('controllers/newsController.php', {
data:{action : this.accion_new, data_new: this.contentnew , imgf : formdata}
})
should simply be be:
this.$http.post('controllers/newsController.php', formdata)
Related
I have to make a post request to an api endpoint, but I get an error status 500.
name: "HttpErrorResponse"
ok: false
status: 500
statusText: "Internal Server Error"
This is my code:
var selectedIds = ["31"];
let sendData = new FormData();
sendData.append('auth', this.dataService.REG_AUTH);
sendData.append('identifier', identifier);
sendData.append('selected[]', selectedIds);
this.http.post<any>('APIENDPOINT', sendData).subscribe(data => {
console.log(data);
}, error => {
console.log(error);
});
The issue is in this line: sendData.append('selected[]', selectedIds); I have no clue how to pass an array to FormData.
This is a working example from our android app. I need to convert this request in angular/typescript syntax:
#JvmSuppressWildcards
#FormUrlEncoded
#POST("APIENDPOINT")
fun addData(
#Field("auth") auth: String,
#Field("identifier") identifier: String,
#Field("selected[]") selected: ArrayList<String>
): Call<ResponseBody>
What I know so far:
It seems angular does not serialize the data, so I tried some hardcoded fixes, but none of these worked:
sendData.append('selected%5B%5D', '%2231%22');
sendData.append('selected%5B%5D', '31');
sendData.append('selected%5B%5D', 31);
sendData.append('selected%5B%5D', '%5B%2231%22%5D');
sendData.append('selected%5B%5D', selectedIds);
sendData.append('selected%5B%5D', JSON.stringify(selectedIds));
If I use selected instead of selected[], then I get no error, but obviously no data is updated, so I am pretty sure it is a serialization/parsing issue.
From this answer:
FormData's append() method can only accept objects of string or blob
type. If you need to append the array, use JSON.stringify() method to
convert your array into a valid JSON string.
formData.append('selected[]', JSON.stringify(selectedIds));
The statusCode 500 is the Internal Server Error, and it's the server-side problem. So, It's better to check the API if it can receive your request or not.
FormData's append() method accept string or blob type So you can use JSON.stringify() method (formData.append('selectedIds', JSON.stringify(selectedIds));). So try this:
let selectedIds = ["31"];
let sendData = new FormData();
sendData.append('auth', this.dataService.REG_AUTH);
sendData.append('identifier', identifier);
sendData.append('selectedIds', JSON.stringify(selectedIds));
this.http.post<any>('APIENDPOINT', sendData).subscribe(data => {
console.log(data);
}, error => {
console.log(error);
});
I seriously confused how to solve this multipart boundary when using Axios, react.js and multipart/formdata. I already stuck for 2 weeks to try to solve this but I feel like I getting closer to solved it but it still stuck no matter what solution I try.
I read and trysome solution from this topic:
how-to-post-multipart-formdata-using-fetch-in-react-native
how-to-send-multipart-form-data-with-antd-upload-react
how-to-send-a-multipart-form-data-from-react-js-with-an-image
this is my create Order function in orderAction.js :
function createOrder(data) {
return dispatch => {
let apiEndpoint = 'order';
let payload = new FormData();
// payload.append('orderImage', data.orderImage);
// console.log("Cek Image : ", data.orderImage);
for (const file of data.orderImage) {
payload.append('orderImage', file)
}
payload.append('userId', data.userId);
payload.append('materialId', data.materialId);
// payload.append('materialId', '5d79930c8c4a882f44b1b0fb');
payload.append('color', data.color);
payload.append('description', data.description);
payload.append('quantity', data.quantity);
payload.append('city', data.city);
payload.append('detailAddress', data.detailAddress);
console.log("Cek Data : ", payload);
fetch(config.baseUrl + apiEndpoint, {
method: 'POST',
headers: {
'Authorization': 'Bearer ' + localStorage.getItem('token'),
'Content-Type' : 'multipart/form-data; boundary=----WebKitFormBoundaryHl8DZV3dBSj0qBVe'
},
body: payload
})
// orderService.post(apiEndpoint, payload)
// .then(res => {
// if(res.data.status === 200) {
// alert(res.data.Message);
// dispatch(createOrderSuccess(res.data));
// history.push('/user-order');
// } else {
// dispatch(createOrderFailed());
// alert(res.data.Message);
// }
// })
};
}
can someone help me to solve this? I'm quite confused with this problem
Edit 1
after try using #narasimha solution finally I got rid the multipart boundary but I got weird behaviour where The data succesfully got encoded like this:
but When I trying check the response the photoUrl return null or `` like this:
and when I try using insomnia or postman it successfully generated the photoUrl like this:
where did I wrong in here?
I had the same problem yesterday. The problem was with content type. I had used the same content type header as you are using. The thing is I removed content type and allowed the fetch () API to handle it automatically. It worked!!
I am trying to upload array of files as multipart/form data.
I use ngx-file-upload v6.0.1
Here is slightly changed method from the library example. I am copying it to show that file is of type File.
public onFileAdded (files: UploadFile[]) {
for (const droppedFile of files) {
if (droppedFile.fileEntry.isFile) {
const fileEntry = droppedFile.fileEntry as FileSystemFileEntry;
fileEntry.file((file: File) => {
this.certificates$.next({
type: ACTIONS.ADD,
value: new Certificate(file, this.getSizeString(file.size), droppedFile.relativePath)
});
});
}
}
Here is onSubmit method:
public submitCertificates(certificates: Certificate[]): Observable<Certificate[]> {
const url = this.completionCertificatesUrl;
const headers = new HttpHeaders({'Content-Type': 'multipart/form-data'});
const formData = new FormData();
certificates.forEach(certificate => {
formData.append('files', certificate.file, certificate.relativePath);
})
return this.http.post<any>(url, formData, {headers}).pipe(
map(data => data)
);
Post request that is sent has following data:
request payload
The problem is that backend (Spring framework which I have no access to and no understanding) throws 500 and does not accept this payload.
I was told that correct payload should look like this:
Content-Type: multipart/form-data; boundary=79ab782d574b45598e6e50d722985144
--79ab782d574b45598e6e50d722985144
Content-Disposition: form-data; name="files"; filename="file-1.json"
content of file-1 file
--79ab782d574b45598e6e50d722985144
Content-Disposition: form-data; name="files"; filename="fil2-2.zip"
content of file-2 file
--79ab782d574b45598e6e50d722985144--
My questions is how can I remove "Content-Type" key from my payload?
I did try a lot of combinations of append(), delete() to no result.
Also, my concern is if the file is really attached to this request. Can I check it anyhow?
I wonder if I am missing the content of the file altogether, because in the example I was provided there is a line "content of file-1" and maybe this is a shortcut for a much longer string that would represent the file content.
Please, help!
My questions is how can I remove "Content-Type" key from my payload?
Look at where you set it:
Delete this line:
const headers = new HttpHeaders({'Content-Type': 'multipart/form-data'});
Delete headers from this line.
return this.http.post<any>(url, formData, {headers}).pipe(
I'm trying to upload a file to the server using react-native-document-picker. The problem I'm facing is I don't know how to upload the file along with a text.In my app there is a portion for file upload also there is an area for writing some text.Then it will get uploaded to the server.So I've done the following.But I'm getting this error after submitting to server
unhandled promise rejection unsupported BodyInit type
updated portion of code
filepick = () => {
DocumentPicker.show({
filetype: [DocumentPickerUtil.images()],
}, (error, res) => {
if (error == null) {
console.log(
res.uri,
res.type, // mime type
res.fileName,
res.fileSize
);
this.setState({
img_uri: res.uri,
img_type: res.type,
img_name: res.fileName
})
} else {
Alert.alert('Message', 'File uploaded failed');
}
});
};
onPressSubmit() {
const data = new FormData();
data.append('file', { uri: this.state.img_uri, type:
this.state.img_type, name: this.state.img_name })
data.append('comment', { text: this.state.text });
AsyncStorage.getItem("userdetail").then(value => {
fetch(GLOBAL.ASSN_URL +`${this.props.id}`, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data',
'Authorization': value
},
body: data
}).then((response) => {
return response.text()
}).then((responseJson) => {
var result = responseJson;
console.log(result);
});
})
}
The function filepick() is called after choosing a file from your device.Please help me to find a solution.How do I upload this to server also how to send text without stringifying it?
body: ({
file: this.state.file,
comment: this.state.text
})
Why are you wrapping body in brackets? Removing them might fix it.
Also see this, https://github.com/facebook/react-native/issues/6025 you might want to stringify the body object, since your content type is not application/json
body: JSON.stringify({
file: this.state.file,
comment: this.state.text
})
Edit
From comments we now know the following
1) You are uploading a file separately.
2) The upload response contains information about the file
3) You are saving the entity in separate server call
4) You need to save file with that entity
The solution below assumes that you have full control over server and you are also handling the file uploading endpoint. Here is the solution
You basically do not need to upload the whole file again with your entity since it is already uploaded on server, all you need to do is to save the reference of the file with entity. Their are two ways to save the reference
1) Just save either the fileName or fileUrl in your entity table and then store the name or url with entity so it will look like this
{
id: 1,
name: 'Cat',
picture: // url or name of picture
}
2) Save the uploaded file in different table, then save the id of the file with your entity, and when you fetch entities get the related file. However if the relationship between entity and file is one to many as in one entity can have many files then you will first need to save the entity and then upload the files with reference of entity. This way your entity will look like this
{
id: 1,
name: 'Cat',
pictures: [{fileName: 'cat1'}, {fileName: 'cat2'}]
}
A web page (front) is calling a service which send a PDF stream as a response :
Here is the front code :
'click .btn': function (event) {
/.../
event.preventDefault();
Http.call(params, (err, res) => { // callback
if (err) console.log(err); // nothing
console.log({ res }); // print below result
const blob = new Blob(
[res.content],
{ type: `${res.headers['content-type']};base64` }
);
saveAs(blob, res.headers['content-disposition'].slice(21));
});
}
Here is the response from the server ( console.log(res) ) : { res : Object } printed in the console.
content: "%PDF-1.4↵1 0 obj↵<<↵/Title (��)↵/Creator (��)↵/Prod ..... lot of characters....%"
data: null,
statusCode: 200,
headers: {
connection: "close",
content-disposition: "attachment; filename=myDoc.pdf"
content-type: "application/pdf",
date: "date",
transfer-encoding: "chunked",
x-powered-by: "Express"
}
However, the PDF is downloaded with no content, it's full blank like corrupted ( But I can see the content in the string ). It works well with the CSV routes ( I send a csv as a stream and download it with the same method and I got the data).
I think there is something with the format %PDF ...% but I didn't manage to find something.
Note : With postman, it works, my PDF is saved, the page is not blank, I got the data. So there is something in the front I am not doing right.
I also tried with :
const fileURL = URL.createObjectURL(blob);
window.open(fileURL); // instead of saveAs
but the result is the same ( but in another tab instead of saved PDF ) blank page.
Any ideas ?
You probably forgot to specify the response type in your inital backend call - from the example you posted "arraybuffer" would be the correct one here, you can check all types here.