Uploading of images
Upload the image using the form submission, the following is the HTML section, enctype= "Multipart/form-data" means not to encode the bytes, upload the file type to be specified. The type= "file" of the input tag specifies the type of upload.
<form action= "/" enctype= "Multipart/form-data" method= "POST" > <input type= "file" name= "Headimg" > </form>
Here is the section that tornado accepts the file
Class Uploadhandler (Basehandler): def post (self): # This part is the uploaded file, want to see more can print self.request look at # The file returns a list of elements for the dictionary imgfile = self.request.files.get (' headimg ') for the img in imgfile: # img has three key-value pairs that can be passed by Img.keys ( View # is ' filename ', ' body ', ' content_type ' clearly corresponds to filename, content (binary) and file type with open ('./static/uploads/' + img[') FileName '], ' WB ') as F: # File contents saved to '/static/uploads/{{filename} ' f.write (f[' body ')
This allows you to access the/static/uploads/file name
Modify the size of a picture
Below will write the resize to the picture
Class Uploadhandler (Basehandler): @tornado. web.authenticated def post (self): # It should be written to the above, in order to show that it was written in the function import time # PIL is a module that operates on images in Python and is interesting to see the from PIL import image # can be used like a file, just stored in memory from Cstringio import Stringio # to determine the size of the upload file sizes size = Int (self.request.headers.get (' content-length ')) if size/1000.0 > 2000:self.write ("Upload picture not can be greater than 2M. ") Imgfile = Self.request.files.get (' headimg ') for IMG in Imgfile: # renaming a file name = str (time.strftime ('%y%m%d% ') ), Time.localtime ()) \ + ' _ ' + self.current_user + ' _headimg.png ' with open ('./static/uploads/' + name, ' WB ') As f: # Image has a variety of open methods, one is Image.open (' Xx.png ') # and the other is Image.open (Stringio (buffer)) Im = Image.open ( Stringio (img[' body ')) # Modify the picture size resize accept two parameters, the first one is the wide-height tuple data, the second is the processing of the picture details, this article represents anti-Aliasing im = Im.resize ((), image . AntiAlias) # Open IO like a file Im_file = Stringio () im.save (im_file, format= ' png ') # This is what gets in IO Im_data= Im_file.getvalue () f.write (Im_data)
This allows the file size to be modified when uploading