Quantcast
Channel: Active questions tagged react-native+typescript - Stack Overflow
Viewing all articles
Browse latest Browse all 6213

How can i upload multipart file in react-native?

$
0
0

i'm trying uploading multipart file to backend server using axios in react-native. I'm setting image using array, but i don't know how to transform object Object to object File. back-end server needs File type. How can i do??

expect log: [object File],

result log: [object Object]

My front code is here

//...//   interface ImageFile {   uri: string;   name: string;   type: string;}   const [images, setImages] = useState([] as ImageFile[]);//. using image picker.//   ImagePicker.showImagePicker(options, async (response) => {     if (response.didCancel) {       return;     }     else if (response.error) {       Alert.alert('에러: '+ response.error);     }     else {       //이미지가무사히선택된것       //기존에있던이미지에더해서배열을더해나감       // console.log(response.data);       setImages([...images, { uri: response.uri, name: response.fileName, type: response.type }]);     }     console.log(images);//post code//  async function toPost() {   let post: Post;   try {     post = await Post.create({ content: comment } as Post);   } catch (e) {     console.log(e);     console.log('포스트생성불가')     return;   }   try {     let a = 0     for (let image of images) {       console.log('image[0]: '+ JSON.stringify(image))       console.log('image[1]: '+ image.type)       console.log('test: '+ test)       await post.createMedia(test, 'IMAGE');       a++;     }   } catch (e) {     console.log(e.response.data);     console.log('이미지생성불가')     return;   }   try {     post.status = 'PUBLIC';     await post.save();   } catch (e) {     console.log(e);     console.log('포스트저장불가');     return;   }   console.log(`저장된글: ${post.content}, 이미지개수: ${post.medias.length}`) }

and my api Code

public async createMedia(file, type: PostMediaType) {    const formData = new FormData();    formData.append('file', { uri: file.uri, name: file.name, type: file.type } as File);    const postMedia = new PostMedia((      await getAxios().post(`/posts/${this.id}/${type}s`, formData, { headers: { 'Content-Type': 'multipart/form-data' } })).data);    if (!this.medias) this.medias = await this.getMedias();    else this.medias.push(postMedia);    return postMedia;  }

Viewing all articles
Browse latest Browse all 6213

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>