Last talk about handling upload avatar is temporarily saved in the local, in fact, this is not appropriate, and the modified avatar to upload to the model is also very troublesome, poor a lot of information, solve the problem
General idea: The user uploads the original image and modifies the data-pil after the modification, save the picture as in-memory bytes-use Ftpstorage to upload to ftp-by rules to modify the avatar path data in model
I. Contentfile\bytesio
fromPILImportImage fromIoImportBytesio fromDjango.core.files.baseImportContentFiledefcrop_image (file, left, top, right, buttom):#Open Pictureim =image.open (file)#crop a pictureCrop_im =Im.crop (left, top, right, buttom)#Save PictureImage_io =Bytesio () crop_im.save (FP=image_io, format='JPEG') returnContentFile (Image_io.getvalue ())
Here is a simple way to write a modified image, because later to upload the image to FTP, so need to use the previous implementation of the Ftpstorage, after reviewing the official documents, It is found that the object content of the save operation of storage can only be the file class in Django.core.files.base and its subclasses, so it is necessary to generate a new file:contentfile, which is the getvalue of the Bytesio class. () method, you can get a bytes
Two. Ftpstorage
def headpic_to_ftp (path, content): storage = ftpstorage () if Storage.exists (path): storage.delete (PATH) storage.save (path, content) else: storage.save (path, content)
Here is a simple way to write a method of uploading, path and file name, you can write the logic in view according to your own needs
Three. View
defuser_my_info_headpic (Request):#Trim Data AcquisitionUsername =Request.user Headpic_name= headpic_path+'/'+STR (username) +'. jpg'file= Request. files['Avatar_file'] Top= Int (float (request). post['avatar_y'])) Buttom= top + int (float (request). post['Avatar_height'])) left= Int (float (request). post['avatar_x'] ) Right= left + int (float (request). post['Avatar_width'])) #Trim AvatarCrop_file =crop_image (file, left, top, right, buttom)#Upload Avatarheadpic_to_ftp (Headpic_name, Crop_file)#Modify Avatar InformationUserInfo = UserInfo.objects.get (username=username) Userinfo.headpic=headpic_name userinfo.save ()returnHttpResponse ("Success")
Cropper+pillow processing upload picture clipping (ii)