在Django中上传后,如何获取文件的绝对路径? [英] How do I get a files absolute path after being uploaded in Django?

查看:140
本文介绍了在Django中上传后,如何获取文件的绝对路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将文件上传到我的数据库,并在上传后将其导入,并最终将数据导出到我的数据库中。我的上传工作正常,但是我不确定上传后如何获取文件的绝对路径。我可以打印出文档的名称,但是如果上传了相同的文档名称,则会附加该文档名称,但是如果我调用 form.cleaned_data ['document']。name,它仍会显示原始文件名。 。我该怎么做才能获取绝对文件路径,然后调用一个函数来开始处理该文件?

I want to upload a file to my database and after it is uploaded import it and eventually export the data into my database. I have the uploading working just fine but I'm not sure how to get the absolute path of the file after it is uploaded. I'm able to print out the name of the document, but if the same document name is uploaded it is appended but still shows the original file name if I call form.cleaned_data['document'].name. What can I do to get the absolute file path and then call a function to start processing this file?

这就是我想要做的:


  • 用户上传.csv文件

  • 文件被保存在db中(带有描述和文件路径。File路径已正确存储在db中)

  • 获取刚刚上传的文件的文件位置

  • 开始处理此文件以转换.csv数据并存储在数据库中

  • User uploads a .csv file
  • File gets saved in db (with a description and file path. File path is getting stored properly in db)
  • Get file location of file that was just uploaded
  • Start to process this file to convert the .csv data and store in database

models.py

models.py

from django.db import models

# Create your models here.
class Document(models.Model):
    description = models.CharField(max_length=255, blank=True)
    document = models.FileField(upload_to='documents/')
    uploaded_at = models.DateTimeField(auto_now_add=True)

views.py

from django.shortcuts import render, redirect
from django.views import View
# Create your views here.

from .forms import DocumentForm
from .models import Document   

class  FileUpload(View):
    def post(self, request):
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            print()
            print(form.cleaned_data['document'].name)
            form.save()
            return redirect('main_db_model:home')
        else:
            return render(request, 'file_upload_form.html', {
                'form': form
            })

    def get(self, request):
        form = DocumentForm()
        return render(request, 'file_upload_form.html', {
            'form': form
        })

forms.py

from django import forms
from .models import Document

class DocumentForm(forms.ModelForm):
    class Meta:
        model = Document
        fields = ('description', 'document', )

file_upload_form.html(模板):

file_upload_form.html (template):

{% extends "base.html" %}

{% block content %}
  <form method="post" enctype="multipart/form-data">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Upload</button>
  </form>
      {% if saved %}
         <strong>Your profile was saved.</strong>
      {% endif %}
  This is the form page
  <p><a href="{% url 'main_db_model:home' %}">Return to home</a></p>

    <p>Uploaded files:</p>
      <ul>
        {% for obj in documents %}
          <li>
            <a href="{{ obj.document.url }}">{{ obj.document.name }}</a>
            <small>(Uploaded at: {{ obj.uploaded_at }})</small>
            {{ obj.document.url }}
          </li>
        {% endfor %}
      </ul>
{% endblock %}


推荐答案

我建议您将此 upload_to ='documents /'更改为 upload_to ='documents /%Y /%m /%d',为什么呢?这可以处理 documents / 路径内的巨大文档文件。

Previously, I suggest you to change this upload_to='documents/' to upload_to='documents/%Y/%m/%d', why? this to handle huge document files inside your path of documents/.

form.cleaned_data ['document'] (或 request.FILES ['document'] )返回< a href = https://docs.djangoproject.com/zh-cn/dev/ref/files/uploads/#django.core.files.uploadedfile.UploadedFile rel = nofollow noreferrer> UploadedFile 对象。当然 form.cleaned_data ['document']。name 应该只返回一个名称。

form.cleaned_data['document'] (or request.FILES['document']) return a UploadedFile object. of course form.cleaned_data['document'].name should return a name only.

class  FileUpload(View):
    def post(self, request):
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            # this `initial_obj` if you need to update before it uploaded.
            # such as `initial_obj.user = request.user` if you has fk to `User`, 
            # if not you can only using `obj = form.save()`
            initial_obj = form.save(commit=False)
            initial_obj.save()

            # return path name from `upload_to='documents/'` in your `models.py` + absolute path of file.
            # eg; `documents/filename.csv`
            print(initial_obj.document)

            # return `MEDIA_URL` + `upload_to` + absolute path of file.
            # eg; `/media/documents/filename.csv`
            print(initial_obj.document.url)

            form.save()

但是,如果您使用 upload_to ='documents /%Y /%m /%d',您会有所不同。 ,

But you will get a different if you using upload_to='documents/%Y/%m/%d',

print(initial_obj.document)      # `documents/2017/02/29/filename.csv`

print(initial_obj.document.url)  # `/media/documents/2017/02/29/filename.csv`

这篇关于在Django中上传后,如何获取文件的绝对路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆