Javascript 如何在 react-native 中使用 FormData?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32441963/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use FormData in react-native?
提问by phongyewtong
Hi just learn to use js and react-native. I cant use FormData it always shows unsupported bodyinit type. I want to send text rather then JSON.stringify. Can anyone help me? Thanks!
嗨,刚学会使用 js 和 react-native。我不能使用 FormData 它总是显示不受支持的 bodyinit 类型。我想发送文本而不是 JSON.stringify。谁能帮我?谢谢!
var data = new FormData()
data.append('haha', 'input')
fetch('http://www.mywebsite.com/search.php', {
method: 'post',
body: data
})
.then((response) => response.json())
.then((responseData) => {
console.log('Fetch Success==================');
console.log(responseData);
var tempMarker = [];
for (var p in responseData) {
tempMarker.push({
latitude: responseData[p]['lat'],
longitude: responseData[p]['lng']
})
}
this.setState({
marker: tempMarker
});
})
.catch((error) => {
console.warn(error);
})
.done();
回答by bun houth
Here is my simple code FormData with react-native to post request with string and image.
这是我的简单代码 FormData,带有 react-native 来发布带有字符串和图像的请求。
I have used react-native-image-picker to capture/select photo react-native-image-picker
我使用 react-native-image-picker 来捕捉/选择照片 react-native-image-picker
let photo = { uri: source.uri}
let formdata = new FormData();
formdata.append("product[name]", 'test')
formdata.append("product[price]", 10)
formdata.append("product[category_ids][]", 2)
formdata.append("product[description]", '12dsadadsa')
formdata.append("product[images_attributes[0][file]]", {uri: photo.uri, name: 'image.jpg', type: 'image/jpeg'})
NOTEyou can change image/jpeg
to other content type. You can get content type from image picker response.
注意您可以更改image/jpeg
为其他内容类型。您可以从图像选择器响应中获取内容类型。
fetch('http://192.168.1.101:3000/products',{
method: 'post',
headers: {
'Content-Type': 'multipart/form-data',
},
body: formdata
}).then(response => {
console.log("image uploaded")
}).catch(err => {
console.log(err)
})
});
回答by Harborhoffer
This worked for me
这对我有用
var serializeJSON = function(data) {
return Object.keys(data).map(function (keyName) {
return encodeURIComponent(keyName) + '=' + encodeURIComponent(data[keyName])
}).join('&');
}
var response = fetch(url, {
method: 'POST',
body: serializeJSON({
haha: 'input'
})
});
回答by Marson Mao
Providing some other solution; we're also using react-native-image-picker
; and the server side is using koa-multer
; this set-up is working good:
提供一些其他的解决方案;我们也在使用react-native-image-picker
;并且服务器端正在使用koa-multer
;此设置运行良好:
ui
用户界面
ImagePicker.showImagePicker(options, (response) => {
if (response.didCancel) {}
else if (response.error) {}
else if (response.customButton) {}
else {
this.props.addPhoto({ // leads to handleAddPhoto()
fileName: response.fileName,
path: response.path,
type: response.type,
uri: response.uri,
width: response.width,
height: response.height,
});
}
});
handleAddPhoto = (photo) => { // photo is the above object
uploadImage({ // these 3 properties are required
uri: photo.uri,
type: photo.type,
name: photo.fileName,
}).then((data) => {
// ...
});
}
client
客户
export function uploadImage(file) { // so uri, type, name are required properties
const formData = new FormData();
formData.append('image', file);
return fetch(`${imagePathPrefix}/upload`, { // give something like https://xx.yy.zz/upload/whatever
method: 'POST',
body: formData,
}
).then(
response => response.json()
).then(data => ({
uri: data.uri,
filename: data.filename,
})
).catch(
error => console.log('uploadImage error:', error)
);
}
server
服务器
import multer from 'koa-multer';
import RouterBase from '../core/router-base';
const upload = multer({ dest: 'runtime/upload/' });
export default class FileUploadRouter extends RouterBase {
setupRoutes({ router }) {
router.post('/upload', upload.single('image'), async (ctx, next) => {
const file = ctx.req.file;
if (file != null) {
ctx.body = {
uri: file.filename,
filename: file.originalname,
};
} else {
ctx.body = {
uri: '',
filename: '',
};
}
});
}
}
回答by Davit Tvildiani
If you want to set custom content-type for formData item:
如果要为 formData 项设置自定义内容类型:
var img = {
uri : 'file://opa.jpeg',
name: 'opa.jpeg',
type: 'image/jpeg'
};
var personInfo = {
name : 'David',
age: 16
};
var fdata = new FormData();
fdata.append('personInfo', {
"string": JSON.stringify(personInfo), //This is how it works :)
type: 'application/json'
});
fdata.append('image', {
uri: img.uri,
name: img.name,
type: img.type
});
回答by anjaneyulubatta505
Usage of formdata in react-native
在 react-native 中使用 formdata
I have used react-native-image-picker
to select photo. In my case after choosing the photp from mobile. I'm storing it's info in component state
. After, I'm sending POST
request using fetch
like below
我曾经react-native-image-picker
选择照片。在我的情况下,从移动设备中选择了 photp 后。我将它的信息存储在 component 中state
。之后,我POST
使用fetch
如下方式发送 请求
const profile_pic = {
name: this.state.formData.profile_pic.fileName,
type: this.state.formData.profile_pic.type,
path: this.state.formData.profile_pic.path,
uri: this.state.formData.profile_pic.uri,
}
const formData = new FormData()
formData.append('first_name', this.state.formData.first_name);
formData.append('last_name', this.state.formData.last_name);
formData.append('profile_pic', profile_pic);
const Token = 'secret'
fetch('http://10.0.2.2:8000/api/profile/', {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "multipart/form-data",
Authorization: `Token ${Token}`
},
body: formData
})
.then(response => console.log(response.json()))
回答by akshay
I have used form data with ImagePickerplugin. and I got it working please check below code
我在ImagePicker插件中使用了表单数据。我让它工作了请检查下面的代码
ImagePicker.showImagePicker(options, (response) => {
console.log('Response = ', response);
if (response.didCancel) {
console.log('User cancelled photo picker');
}
else if (response.error) {
console.log('ImagePicker Error: ', response.error);
}
else if (response.customButton) {
console.log('User tapped custom button: ', response.customButton);
}
else {
fetch(globalConfigs.api_url+"/gallery_upload_mobile",{
method: 'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
,
body: JSON.stringify({
data: response.data.toString(),
fileName: response.fileName
})
}).then(response => {
console.log("image uploaded")
}).catch(err => {
console.log(err)
})
}
});