溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Flask與Django文件上傳與下載處理

發(fā)布時(shí)間:2024-11-14 17:38:03 來源:億速云 閱讀:78 作者:小樊 欄目:編程語言

Flask和Django都是Python Web框架,它們都支持文件上傳和下載處理。下面分別介紹它們?cè)谖募蟼骱拖螺d方面的實(shí)現(xiàn)方法。

  1. Flask文件上傳與下載處理:

Flask是一個(gè)輕量級(jí)的Web框架,使用Flask處理文件上傳和下載相對(duì)簡(jiǎn)單。

上傳文件:

首先,安裝Flask-Upload庫(kù):

pip install Flask-Upload

然后,創(chuàng)建一個(gè)簡(jiǎn)單的Flask應(yīng)用來處理文件上傳:

from flask import Flask, render_template, request
from flask_uploads import UploadSet, configure_uploads, IMAGES, patch_request_class

app = Flask(__name__)
app.config['UPLOADED_IMAGES_DEST'] = 'static/uploads'
upload_set = UploadSet('images', IMAGES)
configure_uploads(app, upload_set)
patch_request_class(app)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/upload/', methods=['POST'])
def upload():
    file = request.files['file']
    if file and file.filename != '':
        img = upload_set.save(file)
        return f'File {img} uploaded successfully.'
    else:
        return 'No file selected.'

if __name__ == '__main__':
    app.run(debug=True)

創(chuàng)建一個(gè)index.html模板文件,用于上傳文件:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>File Upload</title>
</head>
<body>
    <h1>Upload a File</h1>
    <form action="/upload/" method="post" enctype="multipart/form-data">
        <input type="file" name="file">
        <input type="submit" value="Upload">
    </form>
</body>
</html>

下載文件:

在Flask中,可以使用send_file函數(shù)來下載文件:

from flask import send_file

@app.route('/download/<filename>')
def download(filename):
    return send_file(os.path.join('static/uploads', filename), as_attachment=True)
  1. Django文件上傳與下載處理:

Django是一個(gè)高級(jí)的Web框架,它提供了許多內(nèi)置功能來處理文件上傳和下載。

上傳文件:

首先,在settings.py中配置文件上傳相關(guān)設(shè)置:

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

然后,在models.py中定義一個(gè)模型來存儲(chǔ)上傳的文件:

from django.db import models

class File(models.Model):
    file = models.FileField(upload_to='uploads/')
    uploaded_at = models.DateTimeField(auto_now_add=True)

接下來,創(chuàng)建一個(gè)表單來處理文件上傳:

from django import forms
from .models import File

class FileUploadForm(forms.ModelForm):
    class Meta:
        model = File
        fields = ['file']

views.py中處理文件上傳:

from django.shortcuts import render, redirect
from .forms import FileUploadForm

def upload_file(request):
    if request.method == 'POST':
        form = FileUploadForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return redirect('success')
    else:
        form = FileUploadForm()
    return render(request, 'upload.html', {'form': form})

創(chuàng)建一個(gè)upload.html模板文件,用于上傳文件:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>File Upload</title>
</head>
<body>
    <h1>Upload a File</h1>
    <form method="post" enctype="multipart/form-data">
        {% csrf_token %}
        {{ form.as_p }}
        <input type="submit" value="Upload">
    </form>
</body>
</html>

下載文件:

views.py中處理文件下載:

def download_file(request, filename):
    file = File.objects.get(filename=filename)
    return FileResponse(open(file.file.path, 'rb'), content_type='application/octet-stream')

最后,在urls.py中添加URL路由:

from django.urls import path
from . import views

urlpatterns = [
    path('upload/', views.upload_file, name='upload_file'),
    path('download/<str:filename>/', views.download_file, name='download_file'),
]

這樣,你就可以使用Django處理文件上傳和下載了。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI