🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
## 一、上传到本地 ### 准备工作: models中创建表: ~~~ class Book(models.Model): name = models.CharField( max_length=40 ) icon = models.ImageField( upload_to="icons" # 指定文件保存的路径名 系统自动创建 ) ~~~ settings中配置存储路径 ~~~ MEDIA_ROOT = os.path.join(BASE_DIR, "static/uploads") ~~~ 生成一个不重复的文件名: ~~~ import uuid,hashlib def get_unique_str(): uuid_str = str(uuid.uuid4()) md5 = hashlib.md5() md5.update(uuid_str.encode('utf-8')) return md5.hexdigest() ~~~ ### 方法一(文件保存到本地和数据库): views视图中的写法: ~~~ def test1(req): if req.method == 'GET': return render(req, 'mybook.html',{'book_name':book.name,'icon':icon_url}) name = req.POST.get('name') myfile = req.FILES.get('icon') book = Book.objects.create(name=name,icon=myfile) #将数据存储到Book表中 return HttpResponse('OK') ~~~ 前端页面写法: ~~~ <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/app/test1/" method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="text" name="name" placeholder="书名"><br> <input type="file" name="icon"><br> <input type="submit" value="提交"> </form> </body> </html> ~~~ 拼接图片的网络路径,可通过该路径在浏览器上显示出图片 ~~~ icon_url = "http://{}/static/uploads/{}".format( req.get_host(), #获取访问的域名加端口 book.icon.url #图片的路径字符串 ) ~~~ ### 方法二(文件保存到本地): views视图中的写法: ~~~ from .myutil import get_unique_str ~~~ ~~~ def test2(req): if req.method == 'GET': return render(req,'mybook.html') else: name = req.POST.get('name') myfile = req.FILES.get('icon') filename = get_unique_str()+'.'+myfile.name.split('.')[-1] # 文件路径 filepath = os.path.join(settings.MEDIA_ROOT,filename) f = open(filepath,'wb') for i in myfile.chunks(): f.write(i) f.close() return HttpResponse('OK') ~~~ 前端页面的写法: ~~~ <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/app/test2/" method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="text" name="name" placeholder="书名"><br> <input type="file" name="icon"><br> <input type="submit" value="提交"> </form> </body> </html> ~~~ ## 二、上传到oss(\*\*\*) 进入阿里云OSS管理控制台,找到配置信息 views视图中的写法 ~~~ import oss2 from io import BytesIO def upload_to_oss(req):  if req.method == 'GET':  return render(req,'mybook.html')  # 将找到的信息填入下面空缺处 endpoint = '' access_key_id = '' access_key_secret = '' bucket_name = '' bucket_name_host = "" # 生成一个认证对象 auth = oss2.Auth(access_key_id, access_key_secret) bucket = oss2.Bucket(auth, endpoint, bucket_name) # 获取文件 f = req.FILES.get("icon") # 实例化io buf = BytesIO() # 写入到内存 for i in f.chunks(): buf.write(i) # 调整指针到开头 buf.seek(0) # 上传 filename = get_unique_str() + "." + f.name.split(".")[-1] bucket.put_object(filename, buf.getvalue())return HttpResponse('ok') ~~~  前端页面写法: ~~~ <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/app/upload_to_oss/" method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="text" name="name" placeholder="书名"><br> <input type="file" name="icon"><br> <input type="submit" value="提交"> </form> </body> </html> ~~~   图片最终会被上传到阿里云OSS管理控制台中你选择的bucket的文件管理中。