<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{# 上传文件的时候必须要在form标签中添加属性 enctype="multipart/form-data" #}
<form method="POST" action="/upload/" enctype="multipart/form-data">
<input type="text" name="user" />
<input type="file" name="img" />
<input type="submit" />
</form>
</body>
</html>
from django.shortcuts import render
import os
# Create your views here.
def upload(request):
if request.method == "POST":
user = request.POST.get("user")
# img = request.POST.get("img") # 所有提交的文件名
img = request.FILES.get('img') # 所有提交的文件
img_name = img.name # 获取文件名
img_abs_name = os.path.join("static", img_name)
with open(img_abs_name, "wb") as f:
for chunk in img.chunks():
f.write(chunk)
return render(request, 'upload.html')
使用js原生XMLHttpRequest对象进行ajax上传文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<input type="text" id="user" name="user" />
<input type="file" id="img" name="img" />
<input type="button" value="上传图片" onclick="uploadFile1();"/>
<script>
// 使用原生的 XMLHttpRequest 上传图片
function uploadFile1() {
var form = new FormData();
form.append("user", document.getElementById("user").value);
// 获取文件对象
var fileObj = document.getElementById("img").files[0];
form.append("img", fileObj);
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4){
// 已经接受到全部响应数据,执行以下操作
var data = xhr.responseText;
console.log(data);
}
};
xhr.open("POST", "/upload/", true);
xhr.send(form);
}
</script>
</body>
</html>
from django.shortcuts import render
from django.shortcuts import HttpResponse
import os
# Create your views here.
def upload(request):
if request.method == "POST":
user = request.POST.get("user")
# img = request.POST.get("img") # 所有提交的文件名
img = request.FILES.get('img') # 所有提交的文件
img_name = img.name
img_abs_name = os.path.join("static", img_name)
with open(img_abs_name, "wb") as f:
for chunk in img.chunks():
f.write(chunk)
return HttpResponse("ok")
return render(request, 'upload.html')
使用jQuery 的ajax上传文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<input type="text" id="user" name="user" />
<input type="file" id="img" name="img" />
<input type="button" value="上传图片" onclick="jQueryAjax();"/>
<script src="/static/jquery/jquery-1.12.4.js"></script>
<script>
function jQueryAjax() {
// 获取文件对象
var fileObj = $("#img")[0].files[0];
// 创建FormData对象
var form = new FormData();
// 将数据封装到对象中
form.append("img", fileObj);
form.append("user", "aa");
$.ajax({
type: "POST",
url: "/upload/",
data: form,
processData: false,
contentType: false, # 不设置请求头
sucess: function (arg) {
console.log(arg);
}
})
}
</script>
</body>
</html>
from django.shortcuts import render
from django.shortcuts import HttpResponse
import os
import json
# Create your views here.
def upload(request):
if request.method == "POST":
user = request.POST.get("user")
# img = request.POST.get("img") # 所有提交的文件名
img = request.FILES.get('img') # 所有提交的文件
img_name = img.name
img_abs_name = os.path.join("static", img_name)
print(img_abs_name)
with open(img_abs_name, "wb") as f:
for chunk in img.chunks():
f.write(chunk)
return HttpResponse("ok")
return render(request, 'upload.html')
使用jQuery 的ajax + iframe 解决浏览器兼容性的问题
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
#container img{
100px;
height: 100px;
}
</style>
</head>
<body>
<iframe id="my_iframe" name="my_iframe" style="display:none" src="" ></iframe>
<form id="fo" method="POST" action="/upload1/" enctype="multipart/form-data">
<input type="text" id="user" name="user" />
<input type="file" id="img" name="img" onchange="uploadFile();" />
<input type="submit">
</form>
<div id="container">
</div>
<script src="/static/jquery/jquery-1.12.4.js"></script>
<script>
function uploadFile() {
$("#container").find("img").remove();
document.getElementById("my_iframe").onload = callback;
document.getElementById("fo").target = "my_iframe";
document.getElementById("fo").submit();
}
function callback() {
// 想获取iframe中的标签必须使用.contents来获取
var text = $("#my_iframe").contents().find('body').text();
var json_data = JSON.parse(text);
if (json_data.status){
// 上传成功
// 生成img标签,预览刚才上传成功的图片
var tag = document.createElement("img");
tag.src = "/" + json_data.data;
tag.className = "img";
$("#container").append(tag);
}else{
alert(json_data.error);
}
}
</script>
</body>
</html>
from django.shortcuts import render
from django.shortcuts import HttpResponse
import os
import json
# Create your views here.
def upload1(request):
if request.method == "POST":
ret = {
"status": False,
"data": None,
"error": None,
}
try:
img = request.FILES.get("img")
img_name = img.name
img_abs_name = os.path.join("static", img_name)
print(img_abs_name)
with open(img_abs_name, "wb") as f:
for chunk in img.chunks():
f.write(chunk)
ret["status"] = True
ret["data"] = img_abs_name
except Exception as e:
ret["error"] = str(e)
return HttpResponse(json.dumps(ret))
return render(request, "upload1.html")