zoukankan      html  css  js  c++  java
  • django中的python文件上传到本地

    文件保存到本地

    1.准备工作

    STATIC_URL = '/static/'
    
    STATICFILES_DIRS=[
         os.path.join(BASE_DIR,'static')
    ]
    
    #定义上传文件夹的路径
    UPLOAD_ROOT = os.path.join(BASE_DIR,'static/upload')
    

    1.2view视图

    #导包
    import uuid
    # 导入上传文件夹配置
    from mydjango.settings import UPLOAD_ROOT
    import os
    # 导入类视图
    from django.views import View
    from rest_framework.response import Response
    from rest_framework.views import APIView
    
    (一)
    class UploadFile(APIView):
    
        def post(self,request):
            #接受参数
            myfile = request.FILES.get('file')
            print(myfile)                         ps:如果上传的图片是中文名称, QQ图片20200210134035.jpg",需要将 " 替换掉
            # 上传的文件是一个对象
            myfilename=myfile.name.replace('"','')
    
            #建立文件流对象   使用相对路径引入       二进制流写入
            f = open(os.path.join(UPLOAD_ROOT,myfilename),'wb')
            #写入
            for chunk in myfile.chunks():
                f.write(chunk)
            f.close()
            return Response({'filename':myfilename})
    
    
    (二)
    class UploadFile(APIView):
    
        def post(self,request):
            #接受参数
            myfile = request.FILES.get('file')
            myfile.name=str(uuid.uuid4())+'.png'
    
            #建立文件流对象;并将文件上传到settings里指定的路径
            f = open(os.path.join(UPLOAD_ROOT,'',myfile.name),'wb')
            #写入
            for chunk in myfile.chunks():
                f.write(chunk)
            f.close()
            return Response({'filename':myfile.name})
    

    1.3vue

    <template>
      <div>
    	  <myheader></myheader>
    
    	<section class="featured-block text-center">
    		<div class="container">
    
          <div>
            //页面显示图片
            <img :src="src">                
            //自适应
            <Avatar :src='src' :width='150' fit='fill'></Avatar>
          </div>
    
          <table>
            <tr>
              <td>用户头像</td>
              <input type="file" @change="upload">
            </tr>
          </table>
    			
    
    		</div>
    	</section>
        
    </div>
      
    </template>
    
    
     
    <script>
    //导入组件
    import myheader from './myheader.vue'
    export default {
      data () {
        return {
          src:''
    
        }
      },
      components: {
        'myheader':myheader,
      },
      methods: {
        //定义提交事件
        upload(e){
          //获取文件
          let file = e.target.files[0]
          //声明表单参数
          let data = new FormData()
                    //文件key(要和后端接受文件参数名一致) 文件实体,文件名称
          data.append('file',file,file.name)
          //声明请求头
          let config = {headers:{'Content-Type':'multipart/form-data'}}   
          this.axios.post('http://127.0.0.1:8000/upload/',data,config)
          .then(res=>{
            console.log(res)
            this.src = 'http://127.0.0.1:8000/static/upload/'+res.data.filename
          })
        }
    
    
      },
     
    }
    
    
    </script>
     
    <style>
    /* //标签选择器 */
    td{
      padding: 10px
    }
    .imgcode{
      cursor: pointer;
    }
    
    
    </style>
  • 相关阅读:
    03 重定向,请求转发,cookie,session
    02 http,servlet,servletconfig,HttpServletRequest ,HttpServletResponse
    02 JDBC相关
    01 mysql
    16 反射,枚举,新特性
    13 递归练习
    12 IO流
    11 异常
    兼容当前五大浏览器的渐变颜色背景gradient的写法
    Electron Browser加载iframe(webview src属性)
  • 原文地址:https://www.cnblogs.com/bronyaa/p/12801088.html
Copyright © 2011-2022 走看看