代码改变世界

鼠标右键发布文件到远程服务器

2016-11-23 18:03  snryang  阅读(500)  评论(0编辑  收藏  举报

经常需要单个更新文件到Web服务器,总是需要远程链接,复制,粘贴,还要核对目录层次,太繁琐。
所以我想,当我修改某个文件后,点击右键,选择postFile即可将选中的文件上传到服务器。

需要服务器端支持,我的是.net项目,所以直接在项目中增加了以下代码

    [HttpPost]
    [ValidateInput(false)]
    public ContentResult PostFile(string file, string content, string sign) {
        if (sign != "123") return Content("error");
        var filePath = Server.MapPath(file);
        System.IO.File.WriteAllText(filePath, content);
        return Content("ok");            
    }

file:上传文件的相对路径 content:文件内容 sign:可有可无,签名验证,根据团队情况处理。
注意:需要为服务器的IIS_user用户配置写文件的权限。

服务器端所做的工作:接收路径,文件内容,然后必定文件。路径需要根据项目实际情况做约定。(用Node.js来做服务器端会更好)

客户端工作:
1.修改注册表增加一个鼠标右键菜单,右键菜单执行一个批处理文件,并传入选择的文件路径

Windows Registry Editor Version 5.00  
[HKEY_CLASSES_ROOT\*\shell\postFile\command]  
@="postFile.bat \"%1\""  

‘postFile’为菜单名称 poftFile.bat为批处理文件名称,需要放到C:\windows目录下

2.批处理文件中执行Python脚本,并传入文件路径参数

c:\Python27\python.exe d:\postFile.py %*

3.在Python脚本中,调用Http请求上传文件,相关路径需要根据项目约定做处理。

#! usr/bin/python
#coding=utf-8

import sys  
import requests
if __name__ == '__main__':  
    if len(sys.argv)!= 2:  
        sys.exit('argv error!')
#filepath = sys.argv[1]
#posturl='http://xxxx/Home/PostFile'
posturl='http://xxx/Home/PostFile' #测试环境
#posturl='http://xxx/PostFile' #预发布

filepath = sys.argv[1]
webOrAdmin = ''
relativePath = ''
ext = ''
print filepath
if "\\Jwell.Web\\" in filepath:
    print 'web'
    webOrAdmin = 'web'
if "\\Jwell.Admin\\" in filepath:
    print 'admin'
    webOrAdmin = 'admin'
if webOrAdmin == '':
    sys.exit('webOrAdmin error!')
if webOrAdmin == 'web':
    relativePath = filepath[filepath.index("\\Jwell.Web\\")+10:]
    print relativePath
if webOrAdmin == 'admin':
    relativePath = filepath[filepath.index("\\Jwell.Admin\\")+12:]
    print relativePath
    sys.exit('admin not support!')
ext = relativePath[relativePath.rindex('.')+1:]
print 'ext=' + ext
if ext in ['css','js','cshtml']:
    content = open(filepath, "r").read()
    print content
    postdata = {'file': relativePath, 'content': content,'sign':'123'}
    r = requests.post(posturl, data=postdata)
    print r.text
str = raw_input("任意键退出: ")

python脚本中根据项目结构,获取文件相对于某个目录的‘相对路径’,然后将相对路径,文件内容发送到发送指定的URL,只允许上传css js cshtml文件。需要根据您的实际项目情况做相应的处理。

最后整理成一个批处理文件,团队中需要安装Python,运行一次批处理文件即可。

    copy d:\postFile\postFile.py d:\postFile.py
    copy d:\postFile\postFile.bat c:\Windows\postFile.bat
    xcopy d:\postFile\requests\*.* c:\Python27\Lib\requests /s /i
    d:\postFile\postFile.Reg
    pause

python下载地址:https://www.python.org/downloads/release/python-2712/
源代码:https://git.oschina.net/nxwsyang/postfile.git