本地图片上传到服务器,其本质上来讲,就是读取本地图片,复制到服务器,并返回服务器url
前端代码,用的form表单提交,form表单中包含两个文件选择表单元素,选择文件,点击提交按钮,提交form表单
服务端代码如下:
def get_path_format_vars():
return {
"year":datetime.now().strftime("%Y"),
"month":datetime.now().strftime("%m"),
"day":datetime.now().strftime("%d"),
"date":datetime.now().strftime("%Y%m%d"),
"time":datetime.now().strftime("%H%M%S"),
"datetime":datetime.now().strftime("%Y%m%d%H%M%S"),
"rnd":random.randrange(100,999),
}
def GetOutputFileInfo(request, path_format, path_format_vars):
# 将保存的文件路径和配置的静态资源连接起来
outputPath = os.path.join(MEDIA_ROOT, path_format) # 这里MEDIA_ROOT是在settings文件中配置的静态资源路径 MEDIA_ROOT = os.path.join(BASE_DIR, "media")
# 拼接文件名
outputFile = "%(basename)s_%(datetime)s_%(rnd)s.%(extname)s"%path_format_vars
outputFile = outputFile.replace("/","_")
# 将文件夹路径和文件名拼接起来,生成带完整路径的文件路径,用于返回给前端
outputPathFormat = os.path.join(path_format, outputFile)
# 文件路径是否存在,如果不存在则创建一个
if not os.path.exists(outputPath):
os.makedirs(outputPath)
outputPath = outputPath.replace("/","\\")
outputPathFormat = outputPathFormat.replace("/","\\")
return(outputPathFormat, outputPath, outputFile)
def UploadFileToServer(request, filePath, file):
try:
# 以二进制格式写入文件
f = open(filePath, "wb")
for chunk in file.chunks():
f.write(chunk)
except Exception as e:
f.close()
return u"写入文件错误{}".format(e.message)
finally:
f.close()
return "success"
def UploadFile(request):
if not request.method == "POST":
return JsonResponse({"error":u"不支持此种请求"}, safe=False)
/** 这里涉及到一个问题,就是多图上传获取图片,一直以来我们都是直接使用get来获取但是如果是多图,你会发现get拿到的永远只有一个,经过debug调试我们可以看到,request.FILES是一个MultiValueDict类型,这种字典类型是特殊定义的,要取得list,需要用getlist方法
**/
files = request.FILES.getlist("upfile")
if len(files) == 0:
return JsonResponse({"error":u"请至少选择一个文件"}, safe=False)
returnInfors = {} # 定义一个字典用来承载返回值
returnInfos["data"] = []
for file in files:
filename = file.name
fileSize = file.size
# 获取不包括后缀的文件名和文件后缀
upload_origin_name, upload_origin_ext = os.path.splitext(filename)
# 自定义允许上传的文件类型
allType = [".png", ".jpg", ".jpeg", ".gif", ".bmp"]
# 判断文件上传类型
if not upload_origin_ext in allType:
return JsonResponse({"error":u"服务器不允许上传%s类型的文件"%upload_origin_ext}, safe = False)
# 判断上传文件的大小
maxSize = 10485760 # 自定义上传文件大小限制10M
if fileSize > maxSize:
return JsonResponse({"error":u"文件大小不能超过%s"}%maxSize)
# 校验做完了,开始正式上传文件
path_format_var = get_path_format_vars() # 获取时间相关参数,用于拼接文件名
path_format_var.update({
"basename":upload_origin_name,
"extname":upload_origin_ext[1:],
"filename":filename
})
# 取得文件输出的路径
outputPathFormat = "forum/images"
outputFormat, outputPath, outputFile = GetOutputFileInfo(request, outputPathFormat , path_format_vars)
# 开始写入文件
state = UploadFileToServer(request, outputPath, outputFile)
# 写完,将结果返回给前端
mediaurl = urljoin(MEDIA_URL, outputFormat) # MEDIA_URL 也是settings文件中配置的静态资源路径 MEDIA_URL = '/media/'
# 将绝对路径返回给前端
abs_url = request.build_absolute_uri(mediaurl)
return_info = {
"url":abs_url,
"original":upload_origin_name,
"type":upload_origin_ext,
"size":fileSize,
"state":state
}
returnInfos["data"].append(return_info)
return JsonResponse(returnInfos)
def GetFileUpload(request):
return UploadFile(request)