最近在寫一個tornado 與 angularJS 搭建的一個web項目,剛實現了一個圖片上傳功能,還比較簡陋,簡單的在這做個筆記。
首先,前端通過angular提交文件:
//upload.html
<input type="file" name="file"
onchange="angular.element(this).scope().uploadFile(this.files)"/>
//upload.js
$scope.uploadFile = function (files) {
var fd = new FormData();
fd.append("file", files[0]);
$http.post("/api/upload", fd, {
withCredentials: true,
headers: {'Content-Type': undefined},
transformRequest: angular.identity
}).success(function (data) {
console.log("do something");
});
};
只貼了上傳文件的部分代碼,controller就不在此贅述了。
然后,通過tornado接收表單文件并保存圖片:
DIR = "/upload/media/"
class UploadHandle(tornado.web.RequestHandler):
def post(self, *args, **kwargs):
fileinfo = self.request.files["file"][0]
fname = fileinfo['filename']
cname = DIR + "test" +"."+fname.split(".")[-1]
fh = open(cname, 'w')
fh.write(fileinfo['body'])
self.finish("success")