用阿里云SDK配合Python及ruby及html 上传Excel至oss
标签(空格分隔): ruby
author:qsl
阅读前须知
1、ruby的文件由于网速问题,不好下载,可访问
2、为什么不直接使用Python,中间为何还加了ruby;是因为使用阿里云的Python的示例,上传的Excel文件下载后打不开,当时就不继续深入优化了,最后改为ruby,其次是也想了解下ruby这门语言的安装及使用。
可以先看下整体的项目前端页面,前端页面没有用CSS渲染,只是简单将功能实现
1、html代码
需要将此页面放至nginx下运行
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="static/jquery-3.6.1.js"></script>
</head>
<body>
<p>
**请将设备导入模板在此处上传,并且文件名需要完全按照“设备导入模板 .xlsx”命名,注意后缀前面有一个空格
</p>
<form action="http://xxxxx:36510/uploader" method="POST" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" value="上传至服务器" />
</form>
</body>
</html>
2、Python代码
python需要安装一些模块,flask,request
# -*- coding: utf-8 -*-
#Author:qsl
from flask import Flask, render_template, request
import os
from werkzeug.utils import secure_filename
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = '/opt/oss_bucket/upload'
#配合前端上传按钮的函数
@app.route('/uploader',methods=['GET','POST'])
def uploader():
if request.method == 'POST':
f = request.files['file']
print(request.files)
filename = f.filename
f.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
return render_template('upload_sucessful.html')
@app.route("/", methods=['POST'])
def index():
os.system("ruby /root/ruby/aliyun_upload.rb") #执行底下那段ruby的代码,主要是上传接口
return 'msg: upload file sucessful'
if __name__ == '__main__':
app.run(host='10.0.1xxx', port=36510)
app.run(debug=True)
3、安装ruby,二进制安装
#网络原因可能下载很慢,可以至代码仓库上下载
wget http://cache.ruby-lang.org/pub/ruby/2.7/ruby-2.7.0.tar.gz
tar zxvf ruby-2.7.0.tar.gz
./configure --prefix=/usr/local/ruby --with-opessl-dir=/usr/ruby/openssh/openssl-1.0.2l
./configure --with-openssl-dir=/app/openssl-1.0.2l/ssl
make && make install
4、下载阿里云SDK并安装
gem install aliyun-sdk --clear-sources --source https://gems.ruby-china.com
但是在执行ruby代码之前需要安装ruby及下载阿里云的SDK
5、ruby 代码
require 'aliyun/oss'
client = Aliyun::OSS::Client.new(
# Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
endpoint: 'https://oss-cn-hangzhou.aliyuncs.com',
# 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
access_key_id: 'xxxxxx', access_key_secret: xxxxx')
# 填写Bucket名称,例如examplebucket。
bucket = client.get_bucket('xxxx-bucket')
# my-object填写Object完整路径,完整路径中不能包含Bucket名称。
# local-file填写本地文件的完整路径。
bucket.put_object('xxxrttemplate/xx导入模板 .xlsx', :file => '/opt/xx导入模板 .xlsx')
bucket.set_object_acl('xxxrttemplate/xx导入模板 .xlsx', Aliyun::OSS::ACL::PUBLIC_READ)
acl = bucket.get_object_acl('xxxrttemplate/xx导入模板 .xlsx')
puts acl # public-read