2019独角兽企业重金招聘Python工程师标准>>>
最近看了下ruby on rails,试着把Dynamic Web TWAIN集成到ruby on rails中。这里分享下如何在rails中用几行代码搞定文件上传。
参考原文:How to Load, Scan and Upload Files with Ruby on Rails
作者:Desmond Shaw
翻译:yushulx
软件安装
Dynamic Web TWAIN 11.1
Ruby 2.1.7
Ruby Development Kit
在Windows上不要选择Ruby 2.2,不然在运行rails server的时候会报错:
nokogiri不支持,详情可以阅读https://github.com/sparklemotion/nokogiri/issues/1256。
Rails创建工程的基本步骤
安装rails:
gem install rails
创建应用:
rails new dwt
cd到dwt
启动服务
rails server
访问http://localhost:3000
Rails集成Dynamic Web TWAIN上传文件
创建controller
rails generate controller twainscanning home
把< Dynamic Web TWAIN directory >\Resources拷贝到< Rails Project >\public\Resources。
打开< Rails Project >\app\views\twainscanning\home.html.erb添加下面的代码:
DWT with Ruby
DWT with Ruby
打开< Rails Project >\app\controller\application_controler.rb注释掉:
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
#protect_from_forgery with: :exception
end
打开< Rails Project >\config\routes.rb 添加映射:
Rails.application.routes.draw do
get 'twainscanning/home'
root 'twainscanning#home'
post 'upload/' => 'twainscanning#upload'
end
打开< Rails Project >\app\controller\twainscanning_controller.rb添加文件上传代码:
class TwainscanningController < ApplicationController
def home
end
def upload
uploaded_io = params[:RemoteFile]
upload_dir = Rails.root.join('public', 'upload')
unless Dir.exist?(upload_dir)
Dir.mkdir(upload_dir)
end
File.open(Rails.root.join('public', 'upload', uploaded_io.original_filename), 'wb') do |file|
file.write(uploaded_io.read)
end
respond_to do |format|
format.html.any { render text: "Successfully uploaded!"}
end
end
end
运行服务:
源码
https://github.com/dynamsoftsamples/dwt-ruby-on-rails