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>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM