使用Form表单上传文件

  • upload.html
<!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>
  • views.py
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')

上传完之后可以通过链接 “http://127.0.0.1:8000/static/文件名” 打开图片

使用js原生XMLHttpRequest对象进行ajax上传文件

  • upload.html
<!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>
  • views.py
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上传文件

该方法需要借助js原生的FormData()将数据封装到该对象中,并且不支持低版本的浏览器,例如ie5、ie6

  • upload.html
<!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>
  • views.py
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 解决浏览器兼容性的问题

  • upload1.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style> #container img{
width: 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>
  • views.py
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")

Django之上传文件的更多相关文章

  1. django之上传文件和图片

    文件上传:文件上传功能是网站开发中必定会使用到的技术,在django项目中也是如此,下面会详细讲述django中上传文件的前端和后端的具体处理步骤: 前端HTML代码实现: 1.在前端中,我们需要填入 ...

  2. (转)django上传文件

    本文转自:http://www.cnblogs.com/linjiqin/p/3731751.html 另:  本文对原文做了适当修改 更为详细的介绍可以参考官方文档. emplate html(模板 ...

  3. django上传文件

    template html(模板文件): <form enctype="multipart/form-data" method="POST" action ...

  4. 实现简单的django上传文件

    本文用django实现上传文件并保存到指定路径下,没有使用forms和models,步骤如下: 1.在模板中使用form表单,因为这个表单使用于上传文件的,所以method属性必须设置为post,而且 ...

  5. 8. Django系列之上传文件与下载-djang为服务端,requests为客户端

    preface 运维平台新上线一个探测功能,需要上传文件到服务器上和下载文件从服务器上,那么我们就看看requests作为客户端,django作为服务器端怎么去处理? 对于静态文件我们不建议通过dja ...

  6. FTP文件操作之上传文件

    上传文件是一个比较常用的功能,前段时间就做了一个上传图片的模块.开始采用的是共享文件夹的方式,后来发现这种方法不太好.于是果断将其毙掉,后来选择采用FTP的方式进行上传.个人感觉FTP的方式还是比较好 ...

  7. Django上传文件和上传图片(不刷新页面)

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  8. Django上传文件的那些参数

    # ################## 默认文件上传配置 ######################## from django.core.files.uploadhandler import M ...

  9. 20-1 django上传文件和项目里上传头像如何查看

    一 普通上传方式 1 views def upload(request): if request.method == "POST": # print(request.POST) # ...

随机推荐

  1. 整型数组处理算法(八)插入(+、-、空格)完成的等式:1 2 3 4 5 6 7 8 9=N[华为面试题]

    有一个未完成的等式:1 2 3 4 5 6 7 8 9=N 当给出整数N的具体值后,请你在2,3,4,5,6,7,8,9这8个数字的每一个前面,或插入运算符号“+”,或插入一个运算符号“-”,或不插入 ...

  2. muduo源代码分析--我对muduo的理解

    分为几个模块 EventLoop.TcpServer.Acceptor.TcpConnection.Channel等 对于EventLoop来说: 他仅仅关注里面的主驱动力,EventLoop中仅仅关 ...

  3. JavaScript获取和设置CheckBox状态

    注意: 针对单个复选框的情况! var obj = document.getElementById("s1"); var value = obj.checked; alert(va ...

  4. playframework简单介绍

    官方网站: https://www.playframework.com/documentation/2.5.x/Home 简介 编辑 Play!是一个full-stack(全栈的)Java Web应用 ...

  5. C#程序调用cmd执行命令-MySql备份还原

    1.简单实例 //备份还原mysql public static void TestOne() { Process p = new Process(); p.StartInfo.FileName = ...

  6. c - 逆序/正序输出每位.

    #include <stdio.h> #include <math.h> /* 判断一个正整数的位数,并按正序,逆序输出他们的位. */ int invert(int); vo ...

  7. java下udp的DatagramSocket 发送与接收

    发送 package cn.stat.p4.ipdemo; import java.io.BufferedReader; import java.io.IOException; import java ...

  8. win7 删除服务

    以管理员身份运行命令行工具. 输入 sc delete "服务名"   如若服务名有特殊字符需要加引号. sc dekete apache_pn

  9. 使用redis缓存加索引处理数据库百万级并发

    使用redis缓存加索引处理数据库百万级并发 前言:事先说明:在实际应用中这种做法设计需要各位读者自己设计,本文只提供一种思想.准备工作:安装后本地数redis服务器,使用mysql数据库,事先插入1 ...

  10. GO语言练习ONE