Upload file - lazaronixon/react-native-turbolinks GitHub Wiki
This Wiki show you how to use React Native Turbolinks integrated with React Native Image Picker to upload files to rails.
$ yarn add react-native-image-picker
$ cd ios && pod install && cd .. # CocoaPods on iOS needs this extra step
class ApplicationController < ActionController::Base
skip_before_action :verify_authenticity_token # Insecure, you need provide another solution
end
import React, { Component } from 'react'
import Turbolinks from 'react-native-turbolinks'
import ImagePicker from 'react-native-image-picker'
const BASE_URL = 'http://192.168.1.104:3000'
const ARTICLES_UPLOAD_REGEX = /articles\/(.*?)\/upload/
export default class App extends Component {
componentDidMount() {
Turbolinks.addEventListener('turbolinksVisit', this.handleVisit)
Turbolinks.startSingleScreenApp({url: `${BASE_URL}/articles`})
}
handleVisit = (data) => {
if (data.path.match(ARTICLES_UPLOAD_REGEX)) {
this.handleUpload(data.path)
} else {
Turbolinks.visit({url: data.url, action: data.action})
}
}
handleUpload = (path) => {
ImagePicker.showImagePicker({}, photo => {
if (photo.uri) {
fetch(url(), { method: 'put', headers: headers(), body: body() }).then(res => Turbolinks.visit({url: res.url}))
function url() {
return `${BASE_URL}/articles/${path.match(ARTICLES_UPLOAD_REGEX)[1]}`
}
function headers() {
return new Headers({ 'Accept': 'application/json' })
}
function body() {
const data = new FormData()
data.append('article[photo]', { uri: photo.uri, type: photo.type, name: photo.fileName })
return data
}
}
});
}
render() { return null }
}
<p id="notice"><%= notice %></p>
<h1>Articles</h1>
<table>
<thead>
<tr>
<th>Title</th>
<th>Text</th>
<th colspan="4"></th>
</tr>
</thead>
<tbody>
<% @articles.each do |article| %>
<tr>
<td><%= article.title %></td>
<td><%= article.text %></td>
<td><%= link_to 'Show', article %></td>
<td><%= link_to 'Edit', edit_article_path(article) %></td>
<td><%= link_to 'Upload', "articles/#{article.id}/upload" %></td>
<td><%= link_to 'Destroy', article, method: :delete, data: { confirm: 'Are you sure?', remote: true } %></td>
</tr>
<% end %>
</tbody>
</table>
<br>
<%= link_to 'New Article', new_article_path %>