文件上传三种方式

本人花费半年的时间总结的《Java面试指南》已拿腾讯等大厂offer,已开源在github ,欢迎star!

本文GitHub https://github.com/OUYANGSIHAI/JavaInterview 已收录,这是我花了6个月总结的一线大厂Java面试总结,本人已拿大厂offer,欢迎star

原文链接:blog.ouyangsihai.cn >> 文件上传三种方式

点击上方”python宝典”,关注获取python全套视频,

技术文章第一时间送达!

需求

上传图片在页面显示

Form表单上传


!DOCTYPE html
html lang="en"
head
   meta charset="UTF-8"
   titleTitle/title
/head
body
   form method="POST" action="/upload.html" enctype="multipart/form-data"
       input type="text" name="user" /
       input type="file" name="fafafa" /
       input type="submit" value="提交" /
   /form

   div
       {% if img %}
           img style="height: 200px;width: 200px;" src="/{{ img }}" /
       {% endif %}
   /div
   script src="/static/jquery-2.1.4.min.js"/script
   
/body
/html

//后台代码
from django.shortcuts import render
import os
def upload(request):
   if request.method == 'GET':
       return render(request,'upload.html')
   elif request.method == "POST":
       user = request.POST.get('user')
       fafafa = request.POST.get('fafafa')
       obj = request.FILES.get('fafafa')

       file_path = os.path.join('static','upload',obj.name)
       f = open(file_path, 'wb')
       for chunk in obj.chunks():
           f.write(chunk)
       f.close()
       ret = {'status': True, 'path': file_path}
       return render(request,"upload.html",{'img':file_path})

缺点:上传后整个页面会刷新,不好

Ajax上传


!DOCTYPE html
html lang="en"
head
   meta charset="UTF-8"
   titleTitle/title
   style
       .container img{
           width: 200px;
           height: 200px;
       }
   /style
/head
body
   input ID="v1" name="user" placeholder="用户"
   input type="file" name="fafafa" id="img" /
   input type="button" value="提交XML" onclick="UploadXML()" /
   input type="button" value="提交JQ" onclick="Uploadjq()" /
   div id="imgs"

   /div
/body
   script src="/static/jquery-2.1.4.min.js"/script
   script
       function UploadXML() {
           var dic = new FormData();
           dic.append('user', $('#v1').val());
           dic.append('fafafa', document.getElementById('img').files[0]);

           var xml = new XMLHttpRequest();
           xml.open('post', '/upload.html', true);
           xml.onreadystatechange = function () {
               if(xml.readyState == 4){
                   var obj = JSON.parse(xml.responseText);
                   console.log(obj)
                   if(obj.status){
                       var img = document.createElement('img');
                       img.src = "/" + obj.path;
                       document.getElementById("imgs").appendChild(img);
                   }
               }
           };
           xml.send(dic);
       }
       function Uploadjq() {
           var dic = new FormData();
           dic.append('user', $('#v1').val());
           dic.append('fafafa', document.getElementById('img').files[0]);

           $.ajax({
               url: '/upload.html',
               type: 'POST',
               data: dic,
               processData: false,  // tell jQuery not to process the data
               contentType: false,  // tell jQuery not to set contentType
               dataType: 'JSON',
               success: function (arg) {
                   if (arg.status){
                       console.log("111")
                       var img = document.createElement('img');
                       img.src = "/" + arg.path;
                       $('#imgs').append(img);
                   }
               }
           })

       }
   /script

/body
/html

/////后台代码
from app01 import models
import json

from django.shortcuts import render,HttpResponse
import os,json
def upload(request):
   if request.method == 'GET':
       return render(request,'upload.html')
   elif request.method == "POST":
       user = request.POST.get('user')
       print(user)
       fafafa = request.POST.get('fafafa')
       obj = request.FILES.get('fafafa')

       file_path = os.path.join('static','upload',obj.name)
       f = open(file_path, 'wb')
       for chunk in obj.chunks():
           f.write(chunk)
       f.close()
       ret = {'status': True, 'path': file_path}
       return HttpResponse(json.dumps(ret))

****实现了异步刷新,但是部分老版本的浏览器不支持FormData对象

基于iframe实现form提交


!DOCTYPE html
html lang="en"
head
   meta charset="UTF-8"
   titleTitle/title
   style
       .container img{
           width: 200px;
           height: 200px;
       }
   /style
/head
body
   h1基于iframe实现form提交/h1
   form action="/upload.html" method="post" target="iframe_1" enctype="multipart/form-data"
       iframe style="display: none"  id="iframe_1" name="iframe_1" src="" onload="loadIframe();"/iframe
       input type="text" name="user" /br
       input type="file" name="fafafa" /
       input type="submit" value="提交" /
   /form
   div id="imgs"

   /div
/body
   script src="/static/jquery-2.1.4.min.js"/script
   script
       function loadIframe() {
           console.log(1);
           // 获取iframe内部的内容
           var str_json = $('#iframe_1').contents().find('body').text();
           var obj = JSON.parse(str_json);
           if (obj.status){
               var img = document.createElement('img');
               img.src = "/" + obj.path;
               $('#imgs').append(img);
           }
       }
   /script

/body
/html
///后台代码
from django.shortcuts import render,HttpResponse
import os,json
def upload(request):
   if request.method == 'GET':
       return render(request,'upload.html')
   elif request.method == "POST":
       user = request.POST.get('user')
       print(user)
       fafafa = request.POST.get('fafafa')
       obj = request.FILES.get('fafafa')

       file_path = os.path.join('static','upload',obj.name)
       f = open(file_path, 'wb')
       for chunk in obj.chunks():
           f.write(chunk)
       f.close()

       ret = {'status': True, 'path': file_path}

       return HttpResponse(json.dumps(ret))

效果

文件上传三种方式 文件上传三种方式

识别图中二维码,欢迎关注python宝典

本人花费半年的时间总结的《Java面试指南》已拿腾讯等大厂offer,已开源在github ,欢迎star!

本文GitHub https://github.com/OUYANGSIHAI/JavaInterview 已收录,这是我花了6个月总结的一线大厂Java面试总结,本人已拿大厂offer,欢迎star

原文链接:blog.ouyangsihai.cn >> 文件上传三种方式


 上一篇
异常处理 异常处理
点击上方”python宝典”,关注获取python全套视频, 技术文章第一时间送达! 什么是异常异常就是程序运行时发生错误的信号(在程序出现错误时,则会产生一个异常,若程序没有处理它,则会抛出该异常,程序的运行也随之终止),在python中
2021-04-05
下一篇 
项目实战-后台管理系统(二) 项目实战-后台管理系统(二)
点击上方”python宝典”,关注获取python全套视频, 技术文章第一时间送达! 班级管理 classes.html {% extends "layout.html" %} {% block css %} {% endblock %}
2021-04-05