Django和Vue跨域配置以及保存图片到Django目录

Django和Vue跨域配置以及保存图片到Django目录

目录:

F** **#项目根目录

f** **#django目录

urls.py

settings.py

myapp** **#django子应用目录

views.py

admin.py

models.py

serializers.py

urls.py

upload** **#图片保存目录

v** **#vue目录

Django配置

需要pip3 install django-cors-headers
设置secret_key
from django.core.management.utils import get_random_secret_key
get_random_secret_key()
f/settings.py
import os             #顶部导入

###设置secret_key
from django.core.management.utils import get_random_secret_key
get_random_secret_key()

MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',   #添加放到CommonMiddleware上面
    # 'django.middleware.csrf.CsrfViewMiddleware',   #需要注释掉
]

UPLOAD_FILE= os.path.join(BASE_DIR,'upload')        #放在STATIC_URL下面,指定图片保存目录


# 跨域增加忽略,放在最下面
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_ALLOW_ALL = True


CORS_ORIGIN_WHITELIST = (
    'http://127.0.0.1:8000',
)


CORS_ALLOW_METHODS = (
    'DELETE',
    'GET',
    'OPTIONS',
    'PATCH',
    'POST',
    'PUT',
    'VIEW',
)

CORS_ALLOW_HEADERS = (
    'XMLHttpRequest',
    'X_FILENAME',
    'accept-encoding',
    'authorization',
    'content-type',
    'dnt',
    'origin',
    'user-agent',
    'x-csrftoken',
    'x-requested-with',
    'Pragma',
)


f/urls.py
from django.contrib import admin
from django.urls import path,include
#导两个包
from django.views.static import serve
from f import settings



urlpatterns = [
    path('admin/', admin.site.urls),
    path('myapp/',include('myapp.urls')),
    path('upload/<path>',serve,{'document_root':settings.UPLOAD_FILE})
]
myapp/views.py
class Manage_User(GenericViewSet):
    """管理用户数据"""

    @action(methods=["POST"],detail=False)
    def img(self,request):
        image = request.FILES.get('file')
        print(111)
        #以防上传图片会覆盖以前的所以我们拼接一个时间戳解决
        image_name = datetime.datetime.now().strftime('%Y%m%d%H%M%S%f')+image.name
        f = open(os.path.join(settings.UPLOAD_FILE,image_name),'wb')
        #image.chunks() 以二进制流写入文件
        for i in image.chunks():
            f.write(i)
        f.close()
        mes={'code':200,'img_url':'http://127.0.0.1:8000/upload/'+image_name}
        return Response(mes)
myapp/urls.py
from rest_framework.routers import DefaultRouter
from myapp import views

router = DefaultRouter()
router.register('',views.HelloWorldViewSet,basename='hello')
router.register('user',views.Manage_User,basename='user')

urlpatterns = router.urls

Vue配置

v/config/index.js
proxyTable: {
  '/api':{
  target:'http://127.0.0.1:8000/',    #跨域ip
  changeOrigin:true,
  pathRewrite:{
      '^/api':''
      }
  }
v/src/components/HelloWorld.vue
<template>
    <div id="Img">
        商品图片:<input type="file" id="saveimage"><br>
        <button @click="addgoods()">添加</button>
        <img src="" id="img">
    </div>
</template>
<script>
import Qs from 'qs'
export default {
    data(){
        return{

        }
    },
    methods:{
        addgoods:function () {
            //定义data值,方便于传送数据
            var data = new FormData();
            //1.从input框里获取图片
            var img = document.getElementById('saveimage').files[0];
            //2.将图片添加到Formdata中
            data.append('file',img,img.name);
            this.axios({
                    url:'/api/myapp/user/img/',
                    method:'post',
                    data:data,
                    headers:{'Content-Type':'multipart/form-data'}
                }).then((res)=>{
                    document.getElementById('img').src=res.data.img_url
            })
        }
    }
}
</script>


v/src/router/index.js

import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/',
      name: 'HelloWorld',
      component: HelloWorld
    }
  ]
})

v/src/main.js
import axios from 'axios'
Vue.prototype.axios=axios
需要进入v,安装axios
cd v
cnpm install axios --save
上一篇:Django路由配置-快速上手


下一篇:Django框架基础(一)