Flask与Django文件上传与下载处理

发布时间:2024-11-14 17:38:03 作者:小樊
来源:亿速云 阅读:78

Flask和Django都是Python Web框架,它们都支持文件上传和下载处理。下面分别介绍它们在文件上传和下载方面的实现方法。

  1. Flask文件上传与下载处理:

Flask是一个轻量级的Web框架,使用Flask处理文件上传和下载相对简单。

上传文件:

首先,安装Flask-Upload库:

pip install Flask-Upload

然后,创建一个简单的Flask应用来处理文件上传:

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)

创建一个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函数来下载文件:

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是一个高级的Web框架,它提供了许多内置功能来处理文件上传和下载。

上传文件:

首先,在settings.py中配置文件上传相关设置:

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

然后,在models.py中定义一个模型来存储上传的文件:

from django.db import models

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

接下来,创建一个表单来处理文件上传:

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})

创建一个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处理文件上传和下载了。

推荐阅读:
  1. ajax组件怎么在django中使用
  2. 使用Django怎么实现标签筛选

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

django

上一篇:Django的模板上下文管理器Flask模板数据传递

下一篇:Django的Form WizardFlask多步骤表单处理

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》