request.FILES 上传文件问题

2019-04-15 15:50发布

# 上传图片 @csrf_exempt @require_POST def upload_pic(request): data = request.FILES.get('picture', None) if data is None: return gen_resp({"code": ERR_SYSTEM, "msg": "参数picture获取失败"}) #转bytes类型 pic = data.read() # 生成 随机文件名字 now_time = datetime.now().strftime('%Y%m%d%H%M%S') random_str = "%06d" % random.randint(0, 999999) name = now_time + random_str fname = "{}.png".format(name) try: with open(os.path.join(settings.MEDIA_ROOT, 'goods_image', fname), 'wb') as f: f.write(pic) pic_path = HOST_URL + '/media/goods_image/' + fname except Exception as e: log.error('保存图片失败:' + str(e)) res = { 'code': ERR_SERVER, 'msg': '保存图片失败' } return gen_resp(res) res = { 'pic_path': pic_path, 'code': 0, 'msg': '上传图片成功' } return gen_resp(res) 这是一个笨点的方法,功能实现了,先记录一下,后续优化以后再改。 https://blog.csdn.net/changkai456/article/details/80711083