Django+Vue實(shí)現(xiàn)文件上傳下載的項(xiàng)目實(shí)踐
前言
首先我要實(shí)現(xiàn)的頁(yè)面效果是這樣的

當(dāng)點(diǎn)擊上傳文件按鈕,彈出上傳文件的彈出框,可以上傳多個(gè)文件,點(diǎn)擊確定后才正式開(kāi)始上傳

點(diǎn)擊右側(cè)下載按鈕,可以直接下載文件。
上傳功能
后端代碼
settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, '../upload') MEDIA_URL = '/upload/'
這段代碼表示你上傳的文件都會(huì)放在你項(xiàng)目根目錄的upload文件夾下。
views.py
@api_view(('POST',))
@renderer_classes((TemplateHTMLRenderer, JSONRenderer))
def upload_list(request):
# 如果項(xiàng)目根目錄沒(méi)有upload文件夾,會(huì)自動(dòng)給你創(chuàng)建一個(gè)
folder_path = settings.MEDIA_ROOT
if not os.path.exists(folder_path):
os.makedirs(folder_path)
files = request.FILES.getlist('file')
for file in files:
# 這三行代碼就是上傳文件的代碼
f = open(settings.MEDIA_ROOT + "/" + file.name, mode='wb')
for chunk in file.chunks():
f.write(chunk)
# 這段代碼是我要網(wǎng)數(shù)據(jù)庫(kù)里存的一些文件信息,如果不存庫(kù)的話不用寫(xiě)
size = file.size
suffix = file.content_type
createUser = request.user
filePath = settings.MEDIA_URL + file.name
name = file.name
# 上傳完文件記得要關(guān)閉
# 需要注意的一點(diǎn),如果f.close()這句代碼之前,上傳文件之后有報(bào)錯(cuò),那你文件是一直被占用的狀態(tài),刪除也刪不掉,所以一定要做好代碼順序
f.close()
# 往數(shù)據(jù)庫(kù)里存文件信息
Filemanage.objects.create(size=size, suffix=suffix, create_user=createUser, file_path=filePath, name=name)
return JsonResponse(OrderedDict([
('results', {})
], code=status.HTTP_200_OK))前端代碼
<el-upload
class="upload-demo"
ref="upload"
action=""
:auto-upload="false"
:http-request="upload"
:before-upload="beforeAvatarUpload"
multiple
>
<el-button size="small" type="primary">點(diǎn)擊上傳</el-button>
</el-upload>:ref="upload":必須要寫(xiě),因?yàn)槲覀兪鞘謩?dòng)上傳方式。
:auto-upload="false":這里我設(shè)置的不自動(dòng)上傳,如果你沒(méi)有確定按鈕,點(diǎn)擊一起上傳的需求,那你就把值變?yōu)閠ure,你選完文件后會(huì)自動(dòng)上傳。
:http-request="upload":覆蓋默認(rèn)的上傳行為,可以自定義上傳的實(shí)現(xiàn)。
:before-upload="beforeAvatarUpload":上傳文件之前的鉤子,一般用于限制上傳文件大小和類(lèi)型。
multiple:多文件上傳。
methods: {
beforeAvatarUpload(file) {
const isLt2M = file.size / 1024 / 1024 < 200;
if (!isLt2M) {
this.$message.error('上傳頭像圖片大小不能超過(guò)2MB!');
}
return isLt2M;
},
upload(param) {
const formData = new FormData()
formData.append('file', param.file)
mail.uploadFile(formData).then(response => {
console.log('上傳圖片成功')
this.$refs.upload.clearFiles()
}).catch(response => {
console.log(response)
this.$refs.upload.clearFiles()
});
},
}下載功能
后端代碼
def download(request, nid):
# 通過(guò)前臺(tái)傳來(lái)的id查出文件名
row_object = Filemanage.objects.filter(id=nid).first()
# 文件的相對(duì)路徑
file_path = '/upload/' + row_object.name
# 打開(kāi)文件
with open(settings.MEDIA_ROOT + "/" + row_object.name, 'rb') as f:
response = HttpResponse(f.read())
# 設(shè)置Content-Disposition頭以強(qiáng)制瀏覽器下載文件
file_name = os.path.basename(file_path)
response["Content-Type"] = "application/octet-stream"
response['Content-Disposition'] = f'attachment; filename="{file_name}"'
return response前端代碼
<el-button
v-if="permissionList.del"
size="small"
type="success "
@click="download(row)"
>{{ "下載" }}</el-button>methods: {
download(row) {
this.loading = true;
// 這塊是我封裝的axios請(qǐng)求,請(qǐng)求時(shí)要帶著responseType: 'blob',我會(huì)在下面放上我的代碼
file.requestDownload(row.id).then((response) => {
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', row.name);
document.body.appendChild(link);
link.click();
})
.catch((e) => {
console.log(e)
});
},
}requestDownload(id) {
return request({
url: '/tool/download/' + id + '/',
method: 'get',
responseType: 'blob'
})
}到此這篇關(guān)于Django+Vue實(shí)現(xiàn)文件上傳下載的項(xiàng)目實(shí)踐的文章就介紹到這了,更多相關(guān)Django Vue文件上傳下載內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
pandas中的.assign()方法的用法示例小結(jié)
pandas中的.assign()方法用于創(chuàng)建一個(gè)新的DataFrame,其中包含現(xiàn)有DataFrame的副本,并附加了指定的新列或更新了現(xiàn)有列,.assign()方法還可以鏈?zhǔn)绞褂?以添加多個(gè)新列或更新現(xiàn)有列,對(duì)pandas中的.assign()方法感興趣的朋友跟隨小編一起看看吧2023-10-10
Python利用wxPython模塊打造ChatGPT式打字效果程序
這篇文章主要為大家介紹了如何利用Python和wxPython模塊打造一個(gè)ChatGPT式打字效果程序,從而增強(qiáng)用戶體驗(yàn)或提高應(yīng)用程序的可讀性,感興趣的可以了解一下2023-05-05
如何保證Python代碼質(zhì)量,Python測(cè)試與調(diào)試方面的經(jīng)驗(yàn)和心得
本文分享了作者在學(xué)習(xí)Python測(cè)試與調(diào)試方面的經(jīng)驗(yàn)和心得,涵蓋了Python測(cè)試框架(如unittest、pytest)、測(cè)試覆蓋率、單元測(cè)試、集成測(cè)試、調(diào)試技巧、異常處理等內(nèi)容,還對(duì)比了Python與Rust在測(cè)試和調(diào)試方面的差異2026-05-05
Python中使用kitti數(shù)據(jù)集實(shí)現(xiàn)自動(dòng)駕駛(繪制出所有物體的行駛軌跡)
這篇文章主要介紹了Python中使用kitti數(shù)據(jù)集實(shí)現(xiàn)自動(dòng)駕駛——繪制出所有物體的行駛軌跡,本次內(nèi)容主要是畫(huà)出kitti車(chē)的行駛的軌跡,需要的朋友可以參考下2022-06-06
python內(nèi)置HTTP Server如何實(shí)現(xiàn)及原理解析
這篇文章主要為大家介紹了python內(nèi)置HTTP Server如何實(shí)現(xiàn)及原理解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-11-11
flask 框架操作MySQL數(shù)據(jù)庫(kù)簡(jiǎn)單示例
這篇文章主要介紹了flask 框架操作MySQL數(shù)據(jù)庫(kù),結(jié)合實(shí)例形式詳細(xì)分析了flask框架操作MySQL數(shù)據(jù)庫(kù)的連接、表格創(chuàng)建、數(shù)據(jù)增刪改查等相關(guān)使用技巧,需要的朋友可以參考下2020-02-02
關(guān)于win10在tensorflow的安裝及在pycharm中運(yùn)行步驟詳解
這篇文章主要介紹了關(guān)于win10在tensorflow的安裝及在pycharm中運(yùn)行的步驟詳解,本文通過(guò)圖文并茂的形式給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-03-03

