본문 바로가기
django

django file upload & download

by hyundy 2021. 10. 12.

엑셀 데이터를 업로드 해서 필요한 데이터로 가공 한 뒤 다운로드 받는 기능이 필요 하여 찾아 보았다.

 

1. upload 구현

  1-1. settings.py

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

    - media 경로 지정

 

 

  1-2. models.py

from django.db import models


class Document(models.Model):
    title = models.CharField(max_length=200)
    uploadedFile = models.FileField(upload_to="result/")
    dateTimeOfUpload = models.DateTimeField(auto_now=True)

    - 파일을 업로드 해서 저장 하는 FileField() 를 사용

    - upload_to : 업로드 파일 경로 지정

    - settings.py 에 media 경로까지는 지정 되어 있어 실제 경로는 ... /media/result/ 가 된다. 

 

 

  1-3. views.py

from django.shortcuts import render
from . import models


def uploadFile(request):
    if request.method == "POST":
        # Fetching the form data
        fileTitle = request.POST["fileTitle"]
        uploadedFile = request.FILES["uploadedFile"]

        # Saving the information in the database
        document = models.Document(
            title=fileTitle,
            uploadedFile=uploadedFile
        )
        document.save()

    documents = models.Document.objects.all()

    return render(request, "excel/upload-file.html", context={
        "files": documents
    })

    - 화면에서 업로드 된 파일 정보 model 에 저장 

    - models 에서 지정한 경로로 파일 업로드

 

 

  1-4. urls.py

from . import views
from django.urls import path
from django.conf import settings
from django.conf.urls.static import static


app_name = "excel"

urlpatterns = [
    path("", views.uploadFile, name="uploadFile"),
]


if settings.DEBUG:
    urlpatterns += static(
        settings.MEDIA_URL,
        document_root=settings.MEDIA_ROOT
    )

    - 프로젝트 url 에서 앱 url 로 포워딩 시켜놨다.  

 

 

  1-5. upload-file.html

<form action="{% url 'excel:uploadFile' %}" method="POST" enctype="multipart/form-data">
        <input type="text" name="fileTitle" placeholder="Enter a title">
        <input type="file" name="uploadedFile">
        {% csrf_token %}
        <input type="submit" value="Upload">
</form>

<table>
        <tr>
            <th>ID</th>
            <th>Title</th>
            <th>File Path</th>
            <th>Upload Date & Time</th>
        </tr>
        {% for file in files %}
            <tr>
                <td>{{ file.id }}</td>
                <td>{{ file.title }}</td>
                <td>{{ file.uploadedFile.url }}</td>
                <td>{{ file.dateTimeOfUpload }}</td>
            </tr>
        {% endfor %}
    </table>

    - file 업로드 버튼 구현

    - filetitle 지정가능

    - 업로드 데이터 리스트로 출력 해서 확인 가능

 

 

2. download 구현

  2-1. views.py

from . import models
import os
from django.http import FileResponse
from django.core.files.storage import FileSystemStorage


def downloadFile(request):
    file_path = os.path.abspath("media/result/")
    file_name = os.path.basename("media/result/급여지급현황.xlsx")
    fs = FileSystemStorage(file_path)
    response = FileResponse(fs.open(file_name, 'rb'),
                            content_type='application/vnd.ms-excel')
    response['Content-Disposition'] = 'attachment; filename="salary.xlsx"'

    return response

    - 엑셀 데이터 처리후 생성된 파일이 있는 폴더 경로를 찾아 다운로드 한다. 

    - FileSystemStorage,FileResponse 두 클래스가 핵심이다.

    - download 버튼 클릭시 salary.xlsx 파일 다운로드 

 

  2-2. urls.py

urlpatterns = [
    path("download/", views.downloadFile, name="downloadFile")
]

 

 

  2-3. upload-filr.html

    <div>
        <label>첨부 파일</label>
        	<form action="{% url 'excel:downloadFile'  %}">
        	<button type="submit">다운로드</button>
    		</form>
    </div>

    - 버튼을 누르면 파일 다운로드 한다. 

 

'django' 카테고리의 다른 글

Django Form, Serializer  (0) 2021.11.23
Excel data DB insert & the other way  (0) 2021.10.19
Add a module and use a model  (0) 2021.10.18
django mysql connection error  (0) 2021.10.14
django 기본 구조  (0) 2021.10.11