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视图

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})
ps:写入图片的时候,我很纠结,如果用uuid的话,它每次的名字都不一样,然后同一张图片可以添加好多次,但是不用uuid同名的又会覆盖,如果有大神看到能否指定一下子

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>

猜你喜欢

转载自www.cnblogs.com/wonderlandlove/p/12801088.html
今日推荐