首页 > 技术文章 > 你想要的这里都有之上传图片专题篇

luxiaojun 2016-09-25 22:47 原文

Form表单上传(tornado)

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <title>上传文件</title>
</head>
<body>
    <form id="my_form" name="form" action="/index" method="POST"  enctype="multipart/form-data" >
        <input name="fff" id="my_file"  type="file" />
        <input type="submit" value="提交"  />
    </form>
</body>
</html>
html
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import tornado.ioloop
import tornado.web

class LoginHandler(tornado.web.RequestHandler):
    def get(self):
        self.render("login.html")
        
    def post(self, *args, **kwargs):
        file_metas = self.request.files["fff"]  #获取文件的信息
        print(file_metas)
        for meta in file_metas:
            file_name = meta['filename']
            with open(file_name, 'wb') as up:
                up.write(meta['body'])
settings = {
    'template_path': 'tpl',
    'static_path': 'st',

}

application = tornado.web.Application([
    (r"/login", LoginHandler),
], **settings)


if __name__ == "__main__":
    application.listen(8888)
    tornado.ioloop.IOLoop.in
py

FormData对象上传(tornado)

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <input type="file" id="img" />
    <input type="button" onclick="UploadFile();" />
    <script>
        function UploadFile(){
            //获取文件对象
            var fileObj = document.getElementById("img").files[0];
            //创建form对象
            var form = new FormData();
            form.append("k1", "v1");  //为后台发送数据
            form.append("fff", fileObj);
            var xhr = new XMLHttpRequest();
            xhr.open("post", '/login', true);
            xhr.send(form); //发送form表单
        }
    </script>
</body>
</html>
HTML - XMLHttpRequest
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import tornado.ioloop
import tornado.web

class LoginHandler(tornado.web.RequestHandler):
    def get(self):
        self.render("login.html")

    def post(self, *args, **kwargs):

        file_metas = self.request.files["fff"]  #获取文件的信息
        print(file_metas)
        for meta in file_metas:
            file_name = meta['filename']
            with open(file_name, 'wb') as up:
                up.write(meta['body'])
settings = {
    'template_path': 'tpl',
    'static_path': 'static',
}

application = tornado.web.Application([
    (r"/login", LoginHandler),
], **settings)


if __name__ == "__main__":
    application.listen(8899)
    tornado.ioloop.IOLoop.instance().start()
py

AJAX上传(tornado)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="{{static_url('jquery-1.9.1.min.js')}}"></script>
</head>
<body>
<h1>1223</h1>
 <input type="file" id="img" />
    <input type="button" onclick="UploadFile();" />
    <script>
        function UploadFile(){
            var fileObj = $("#img")[0].files[0];
            var form = new FormData();
            form.append("k1", "v1");
            form.append("fff", fileObj);
            $.ajax({
                type:'POST',
                url: '/login',
                data: form,
                processData: false,  // tell jQuery not to process the data
                contentType: false,  // tell jQuery not to set contentType
                success: function(arg){
                    console.log(arg);
                }
            })
        }
    </script>
</body>
</html>
HTML - jQuery
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import tornado.ioloop
import tornado.web

class LoginHandler(tornado.web.RequestHandler):
    def get(self):
        self.render("login.html")

    def post(self, *args, **kwargs):

        file_metas = self.request.files["fff"]  #获取文件的信息
        print(file_metas)
        for meta in file_metas:
            file_name = meta['filename']
            with open(file_name, 'wb') as up:
                up.write(meta['body'])
settings = {
    'template_path': 'tpl',
    'static_path': 'static',
}

application = tornado.web.Application([
    (r"/login", LoginHandler),
], **settings)


if __name__ == "__main__":
    application.listen(8899)
    tornado.ioloop.IOLoop.instance().start()
py

文件上传(django)

a、自定义上传

def upload_file(request):
    if request.method == "POST":
        obj = request.FILES.get('fafafa')
        f = open(obj.name, 'wb')
        for chunk in obj.chunks():
            f.write(chunk)
        f.close()
    return render(request, 'file.html')

b、Form上传文件实例

class FileForm(forms.Form):
    ExcelFile = forms.FileField()
View Code
from django.db import models

class UploadFile(models.Model):
    userid = models.CharField(max_length = 30)
    file = models.FileField(upload_to = './upload/')
    date = models.DateTimeField(auto_now_add=True)
View Code
def UploadFile(request):
    uf = AssetForm.FileForm(request.POST,request.FILES)
    if uf.is_valid():
            upload = models.UploadFile()
            upload.userid = 1
            upload.file = uf.cleaned_data['ExcelFile']
            upload.save()
            
            print upload.file
View Code

利用 iframe标签实现图片上传

a、单张图片的上传(图片上传服务器后把图片路径返回实现预览)

 <form style="display: inline-block" id="upload_img_form" name="form" action="/upload/" method="POST"
          enctype="multipart/form-data">
        {% csrf_token %}
        <a id="fakeFile" class="fake-file">
                <input type="file" name="img" onchange="UploadImage(this);"/>
                <input type="text" name="url" class="hide"/>
        </a>
        <iframe id='upload_img_iframe' name='upload_img_iframe' src="" class="hide"></iframe>
    </form>
html
    function UploadImage(ths) {
        document.getElementById('upload_img_iframe').onload = UploadImageComplete;  //页面加载完成后执行UploadImageComplete函数
        document.getElementById('upload_img_form').target = 'upload_img_iframe';  //设置form提交到iframe
        document.getElementById('upload_img_form').submit(); //#提交到iframe
    }
    function UploadImageComplete() {
        var origin = $("#upload_img_iframe").contents().find("body").text();//#获取图片数据
        var obj = JSON.parse(origin); //#转换成JavaScript对象
        var img = document.createElement('img'); //#创建img标签
        img.src = obj.path; //图片地址
        img.style.width = "200px";
        img.style.height = "180px";
        $("#upload_img_form").append(img);//添加图片
        $('#fakeFile').addClass('hide');
        $('#reUploadImage').removeClass('hide');
        $('#fakeFile').find('input[type="text"]').val(obj.data);//#保存图片地址到隐藏的input标签中
    }
js
def upload(request):
    if request.method == 'POST':
        val = request.POST.get('input_val')
        obj = request.FILES.get('img')
        # temp = os.path.dirname(os.path.dirname(__file__))
        pat = os.path.join('st','img','vote',obj.name)
        path = os.path.join('/','static','img','vote',obj.name)
        print(pat)
        time2 = time.time()
        models.PLAYER.objects.create(name=val,url =path ,time = time2,favour_num=0)
        f = open(pat,'wb')
        for ch in obj.chunks():
            f.write(ch)
        f.close()
        # return render(request,'upload.html',{'path':pat})
        ret = {'path': '/'+os.path.join('static','img','vote',obj.name)}
        import json
        return HttpResponse(json.dumps(ret))
后台

 b、上传多张图片

<form style="display: inline-block" id="upload_img_form" name="form" action="/upload/"
      method="POST" enctype="multipart/form-data">
    {% csrf_token %}
    <a id="fakeFile" class="fake-file"><input type="file" class="file" name="img" multiple
                                              onchange="UploadImage(this);"/>
        <input type="text" name="url" class="hide"/>
    </a>
    <iframe id='upload_img_iframe' name='upload_img_iframe' src="" class="hide"></iframe>
</form>
<span id="img"></span>
htnl
        function UploadImage(ths) {
            var num = $("#img").children().length;
            console.log(num);
            document.getElementById('upload_img_iframe').onload = UploadImageComplete;  //页面加载完成后执行UploadImageComplete函数
            document.getElementById('upload_img_form').target = 'upload_img_iframe';  //设置form提交到iframe
            document.getElementById('upload_img_form').submit(); //#提交到iframe
        }
        function UploadImageComplete() {
            var origin = $("#upload_img_iframe").contents().find("body").text();//#获取图片数据
            var obj = JSON.parse(origin); //#转换成JavaScript对象
            $(obj.path).each(function (x, y) {
                var img = document.createElement('img'); //#创建img标签
                img.src = y; //图片地址
                img.className = "addimg";
                $("#img").append(img);//添加图片
            });
            $('#fakeFile').addClass('hide');
            $('#reUploadImage').removeClass('hide');
            $('#fakeFile').find('input[type="text"]').val(obj.data);//#保存图片地址到隐藏的input标签中
        }
js
def upload(request):
    if request.method == 'POST':
        ret = {'path': []}
        obj = request.FILES.getlist('img', None)
        for i in obj:
            pa = '/'+os.path.join('statics','img','upload_img',i.name)
            ret["path"].append(pa)
            pat = os.path.join('Statics', 'img', 'upload_img', i.name)
            f = open(pat, 'wb')
            for ch in i.chunks():
                f.write(ch)
            f.close()
        import json
        return HttpResponse(json.dumps(ret))
后台

实现本地预览无需上传服务器

方法一:

1、上传单张图片

<input id="upload" type="file" onchange="localShowImage();">
<img id="preview" src="">
    function getOs() {
        var OsObject = "";
        if (navigator.userAgent.indexOf("MSIE") > 0) {
            return "MSIE";
        }
        if (isFirefox = navigator.userAgent.indexOf("Firefox") > 0) {
            return "Firefox";
        }
        if (isSafari = navigator.userAgent.indexOf("Safari") > 0) {
            return "Safari";
        }
        if (isCamino = navigator.userAgent.indexOf("Camino") > 0) {
            return "Camino";
        }
        if (isMozilla = navigator.userAgent.indexOf("Gecko/") > 0) {
            return "Gecko";
        }
    }
    function localShowImage() {
        // IE浏览器获取图片路径
        this.getImgUrlByMSIE = function (fileid) {
            return document.getElementById(fileid).value;
        };
        // 非IE浏览器获取图片路径
        this.getImgUrlByUnMSIE = function (fileid) {
            var f = document.getElementById(fileid).files[0];
            return window.URL.createObjectURL(f);
        };
        var imgsrc = "";
        var fid = "upload";
        if ("MSIE" == getOs()) {
            imgsrc = this.getImgUrlByMSIE(fid);
        } else {
            imgsrc = this.getImgUrlByUnMSIE(fid);
        }

        document.getElementById('preview').src = imgsrc;
    }
js

2、多张图片

<input id="upload" multiple type="file" class="file" onchange="localShowImage();">
<span id="img"></span>
        function getOs() {
        var OsObject = "";
        if (navigator.userAgent.indexOf("MSIE") > 0) {
            return "MSIE";
        }
        if (isFirefox = navigator.userAgent.indexOf("Firefox") > 0) {
            return "Firefox";
        }
        if (isSafari = navigator.userAgent.indexOf("Safari") > 0) {
            return "Safari";
        }
        if (isCamino = navigator.userAgent.indexOf("Camino") > 0) {
            return "Camino";
        }
        if (isMozilla = navigator.userAgent.indexOf("Gecko/") > 0) {
            return "Gecko";
        }
    }
        function localShowImage() {
        // IE浏览器获取图片路径
        this.getImgUrlByMSIE = function (fileid) {
            return document.getElementById(fileid).value;
        };
        // 非IE浏览器获取图片路径
        this.getImgUrlByUnMSIE = function (fileid) {
            var ret = [];
            var f = document.getElementById(fileid).files;
            $(f).each(function (x,y) {
                 ret.push(window.URL.createObjectURL(y))
            });
            return ret;
        };
        var imgsrc = "";
        var fid = "upload";
        if ("MSIE" == getOs()) {
            imgsrc = this.getImgUrlByMSIE(fid);
        } else {
            imgsrc = this.getImgUrlByUnMSIE(fid);
        }

        $(imgsrc).each(function (x, y) {
                var img = document.createElement('img'); //#创建img标签
                img.src = y; //图片地址
                img.className = "addimg";
                $("#img").append(img);//添加图片
            });
    }
js

方法二:

<input type="file" id="files" multiple />
<output id="list"></output>
function handleFileSelect(evt) {
    var files = evt.target.files;

    // Loop through the FileList and render image files as thumbnails.
    for (var i = 0, f; f = files[i]; i++) {

      // Only process image files.
      if (!f.type.match('image.*')) {
        continue;
      }

      var reader = new FileReader();

      // Closure to capture the file information.
      reader.onload = (function(theFile) {
        return function(e) {
          // Render thumbnail.
          var span = document.createElement('span');
          span.innerHTML = 
          [
            '<img style="height: 75px; border: 1px solid #000; margin: 5px" src="', 
            e.target.result,
            '" title="', escape(theFile.name), 
            '"/>'
          ].join('');
          
          document.getElementById('list').insertBefore(span, null);
        };
      })(f);

      // Read in the image file as a data URL.
      reader.readAsDataURL(f);
    }
  }

  document.getElementById('files').addEventListener('change', handleFileSelect, false);
js

 

推荐阅读