Skip to content

Instantly share code, notes, and snippets.

@aleksik
Last active July 26, 2017 10:38
Show Gist options
  • Save aleksik/5190194f972ad58f2d3b6e3cb17396e6 to your computer and use it in GitHub Desktop.
Save aleksik/5190194f972ad58f2d3b6e3cb17396e6 to your computer and use it in GitHub Desktop.
React native image upload
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
}
});
<?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