Last active
July 26, 2017 10:38
-
-
Save aleksik/5190194f972ad58f2d3b6e3cb17396e6 to your computer and use it in GitHub Desktop.
React native image upload
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
import { Button, Image, View, StyleSheet} from 'react-native'; | |
import { ImagePicker } from 'expo'; | |
export default class App extends React.Component { | |
constructor(props) { | |
super(props); | |
this.state = { | |
image: null | |
}; | |
} | |
async pickImage() { | |
let result = await ImagePicker.launchImageLibraryAsync(); | |
if (!result.cancelled) { | |
this.setState({ | |
image: result.uri | |
}); | |
} | |
} | |
async upload() { | |
const body = new FormData(); | |
body.append('uploadedFile', { | |
uri: this.state.image, | |
type: 'image/jpg', | |
name: 'demo.jpg' | |
}); | |
const config = { | |
method: 'POST', | |
headers: { 'Content-Type': 'multipart/form-data' }, | |
body | |
}; | |
const result = await fetch('http://192.168.1.56:8080/api/upload', config); | |
} | |
render() { | |
return ( | |
<View style={styles.container}> | |
<Button | |
title="Pick an image" | |
onPress={this.pickImage.bind(this)} | |
/> | |
{ | |
this.state.image && ( | |
<View> | |
<Image source={{ uri: this.state.image }} style={styles.image} /> | |
<Button title="Upload" onPress={this.upload.bind(this)} /> | |
</View> | |
) | |
} | |
</View> | |
); | |
} | |
} | |
const styles = StyleSheet.create({ | |
container: { | |
flex: 1, | |
backgroundColor: '#fff', | |
alignItems: 'center', | |
justifyContent: 'center', | |
}, | |
image: { | |
width: 200, | |
height: 200 | |
} | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Http\Controllers; | |
use Illuminate\Http\Request; | |
class UploadController extends Controller | |
{ | |
public function upload(Request $request) | |
{ | |
if ($request->hasFile('uploadedFile')) { | |
$request->file('uploadedFile')->store('images'); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment