ajax上传文件并保持文件在media下


发布时间:2020-01-10 08:06    作者: Uncle Hui   已过去:6 月,4 周   阅读总量:280 已被赞:0


要上传文件到media文件下,我们可以这样做:

1.settings.py 配置media路径

MEDIA_URL = '/media/'#url映射
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')     #设置静态文件路径为主目录下的media文件夹

2. 写好前段代码,比如这样:

{% extends 'base.html' %}
{% block head %}
<script src="{% static 'js/piliang_add.js' %}"></script>
{% endblock %}
{% block body %}
<div class="x-body">
        <form class="layui-form" enctype="multipart/form-data">
          <div class="layui-form-item">
              <label for="task_name" class="layui-form-label">
                  <span class="x-red">*</span>批量导入
              </label>
              <div class="layui-input-inline">
                  <input type="file"  name="exc_file" id="uploadForm"
                  autocomplete="off" class="layui-input">
              </div>
          </div>
          <div class="layui-form-item">
              <label class="layui-form-label">
              </label>
              <button  class="layui-btn" id="piliang_add_btn">提交</button>
          </div>
      </form>
    </div>
{% endblock %}
 

 要注意:enctype="multipart/form-data"> 和提交的ID,文件的类型,name,id等

<input type="file"  name="exc_file" id="uploadForm"

 

3.js书写:

 这是一个完整js书写,使用了自己封装的模态提示框,与一般表单不同的地方就在于 FormData()的使用

function Piliang_add() {
    var self = this;
}
Piliang_add.prototype.run = function () {
    var self = this;
    self.add_piliang_Event();
};
Piliang_add.prototype.add_piliang_Event=function () {
      var add_p = $('#piliang_add_btn');
      add_p.click(function (eve) {
          eve.preventDefault();
          var exc_file =$('#uploadForm')[0].files[0];
          var formData = new FormData();
          formData.append('exc_file',$('#uploadForm')[0].files[0]);
          $.ajax({
              url:'../piliang_add/',
              dataType:'json',
              type:'POST',
              data:formData,
              cache: false,
              processData: false,
              contentType: false,
              'success':function (result) {
                  if(result['code']===200){
                      huigege_alert.alertSuccessWithTitle({
                          'title':'提示',
                          'text':'导入成功',
                          'type':'success'
                      });
                  }else{
                       var messageObject = result['message'];
                       if(typeof messageObject === 'string' || messageObject.constructor === String){
                        huigege_alert.alertSuccessWithTitle({
                        'title':'温馨提示',
                        'text':messageObject,
                        'type':'error'
                    });
                    }else{
                        for(var key in messageObject){
                            var messages = messageObject[key];
                            var message = messages[0];
                           huigege_alert.alertSuccessWithTitle({
                        'title':'温馨提示',
                        'text':message,
                        'type':'error'
                    });
                        }
                    }
                }
            },
            'fail': function (error) {
                console.log(error);
            }
          })
      })
};
$(function () {
   var EMAIL_PWD = new Piliang_add();
   EMAIL_PWD.run();
});

 4.views.py处理及URL 的连接

引入:

import os
from django_celery_pro.settings import BASE_DIR

 

def piliang_add(request):
    if request.method == 'POST':
        file = request.FILES.get('exc_file')
        if file != None :
            f=open(os.path.join(BASE_DIR,'media','my_file',file.name),'wb')
            for chunk in file.chunks():
                f.write(chunk)
            f.close()
            return restful.ok()
        else:
           return restful.params_error(message='请选择excl文件上传!')
    else:
        return render(request, 'piliang_add.html')

 

path('piliang_add/', views.piliang_add,name='piliang_add'),

 如果我们在上传文件的时候,顺带要提交一些表单项,我们可以这样:

点赞

0




登陆后方可评论