1. 程式人生 > 實用技巧 >w檔案上傳功能

w檔案上傳功能

上傳檔案流程

vue.js–>axios–>django介面–>file來寫檔案–>檔案操作(可壓縮檔案,可同步到七牛雲-又拍雲)–>提取檔名稱–>vue.js

上傳檔案vue.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
<div>
<table>
<tr>
// Avatar 使圖片展示為圓形
<Avatar :src="src" :width="150" height="150px"></Avatar>
</tr>

<tr>
<td>使用者頭像:</td>
//當圖片發生改變是@change不是click點選
<td><input type="file" @change="upload"></td>
</tr>

</table>

</div>

// return中定義s變數

src:''


//上傳檔案
upload:function (e) {

//獲取檔案
let file = e.target.files[0];
//宣告表單引數
let param = new FormData();

param.append('file',file,file.name);

//宣告請求頭
let config = {headers:{'Content-Type':'multipart/form-data'}};

// 傳送請求
this.axios.post('http://localhost:8000/upload/',param,config).then((res)=>{

console.log(res);

//圖片的路徑要拼接起來
this.src = 'http://localhost:8000/static/upload/'+res.data.filename;

})

}

配置setting檔案上傳路徑

1
2
3
4
5
6
7
8
STATIC_URL = '/static/'

STATICFILES_DIRS[
os.path.join(BASE_DIR,'static')
]

#定義資料夾
UPLOAD_ROOT = os.path.join(BASE_DIR,'static/upload')

上傳檔案介面

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#匯入上傳資料夾配置
from mydjango.settings import UPLOAD_ROOT
import os

#檔案上傳通用類
class UploadFile(APIView):

def post(self,request):

#接收引數
myfile = request.FILES.get('file')

#建立檔案流物件
f = open(os.path.join(UPLOAD_ROOT,'',myfile.name.replace('"','')),'wb')

#寫入
for chunk in myfile.chunks():
f.write(chunk)
f.close()

return Response({'filename':myfile.name.replace('"','')})