【问题标题】:How to rename upload file from input text如何从输入文本重命名上传文件
【发布时间】:2017-11-25 07:46:55
【问题描述】:

我是编码新手,所以我很不擅长。我使用 Django 作为框架。目前这是我用于用户输入的 html 代码。

<html>
<head>
  <title>uploader</title>
  <style>
    h1 {
      font-size: 2em;
      font-weight: bold;
      color: #777777;
      text-align: center
    }
    table {
      margin: auto;
    }
    a {
      text-decoration: none
}
  </style>
</head>

<body>

   <h1>
      {{what}}
      <h3><p style="text-align: left;text-decoration: none;"><a href="{% url 'home' %}">Back</p></a></h3>
  </h1>
 <hr>
  <table>
    <tr>
      <td>
        <form action="upload/" method="POST" enctype="multipart/form-data">
 {% csrf_token %}
 <fieldset>
   Category of the device:<br>
   <input type="text" name="category" value="" required id="cat">
   <br>
   Model:<br>
   <input type="text" name="model" value="" required id="mod">
 <br>
          <input type="submit" value="Upload File" class="submit" name="submit" />
 <input type="file" name="file"/>

 </fieldset>

        </form>


      </td>
    </tr>
  </table>

</body>

</html>

views.py

def home(request):
    return render(request, 'index.html', {'what':'Upload Files'})


def upload(request):
try:
    if request.method == 'POST' and request.FILES['file']:
        try:    
            myfile = request.FILES['file']
            category = request.POST['category']
            model = request.POST['model']
            validate_file_extension(myfile)
            fs = FileSystemStorage(location='uploaded/')
            filename = request.FILES['filename'].name
            handle_uploaded_file(request.FILES['file'], str(request.FILES['file']))
            modified_name = "{}_{}_{}".format(filename, category, modle)
            filename = fs.save(modified_name, myfile)
            return redirect("/success")
        except:
            return redirect("/unsuccessful")
except:
    return redirect("/upload")

def handle_uploaded_file(file, filename):
    if not os.path.exists('uploaded/'):
        os.mkdir('uploaded/')
    with open('uploaded/' + filename, 'wb+') as destination:
        for chunk in file.chunks():
            destination.write(chunk)

如何重命名用户上传的文件,以便将他们输入的文本放在文件名后面,并带有“_”。

例如:

filename = myfile
category = camera 
model    = XYZ123

文件应重命名为“myfile_camera_XYZ123”。

【问题讨论】:

  • 您必须在视图中执行此操作。可以发一下吗?
  • 当然!我已经编辑过了
  • 表单是否与模型相关联?
  • 不,不是。

标签: python html django upload rename


【解决方案1】:

首先获取表单值categorymodel。然后从上传的文件中获取文件名。

category = request.POST['category']
model = request.POST['model']

# And filename
filename = request.FILES['filename'].name


modified_name = "{}_{}_{}".format(filename, category, modle)
filename = fs.save(modified_name, myfile)

【讨论】:

  • 我不明白你想说什么我尝试添加代码但它不起作用。
  • 从表单中获取类别和模型后。并使用 request.FILES['filename'].name 获取原始文件名
  • 然后创建修改后的名称字符串。这有什么不明白的……?
  • 我可以得到类别和型号,但我在这行代码中有 MultiValueDictKeyError:"filename = request.FILES['filename'].name"
  • 哦。对此感到抱歉。我刚才在你的 html 中看到了&lt;input type="file" name="file" /&gt;。所以试试request.FILES['file'].name
【解决方案2】:

这里有一个更好的方式来处理 django 表单。

# forms.py
from django import forms

class UploadFileForm(forms.Form):
    category = forms.CharField(max_length=100)
    model = forms.CharField(max_length=100)
    file = forms.FileField()

# views.py
def upload(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            data = form.cleaned_data
            validate_file_extension(data.file)
            file_ext = data.file.split(".")[-1]
            file_core = data.file.replace('.'+file_ext, '')
            filename = '{0}_{1}_{2}.{3}'.format(file_core, data.category, data.model, file_ext)
            handle_uploaded_file(filename)
            # ... fill the end

【讨论】:

  • 有一个 dict 错误,我不能超过 "file_ext = data.file.split(".")[-1]" 当你说填充结尾时,我该怎么处理例外?如果我将其更改为 else 则显示语法错误
  • forms.py 已修复,我的错。应该更好。根据您的项目,不确定代码是否 100% 有效,但它为您提供了主要思想。
  • 抱歉回复晚了,但是在cmd中显示错误:AttributeError: 'dict' object has no attribute 'file' 有什么意思吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-13
  • 2021-10-25
  • 1970-01-01
  • 2020-08-29
相关资源
最近更新 更多