Django之文件上传

前端 

<!DOCTYPE html>
<html>
<body>

<h2>Upload File</h2>
<form action="/upload_file/" method="post" enctype="multipart/form-data">
  Select file to upload:
  <input type="file" name="file" id="file">
  <input type="submit" value="Upload File" name="submit">
</form>

<script>
  // JavaScript 用于处理文件上传
  const form = document.querySelector('form');
  form.addEventListener('submit', (e) => {
    e.preventDefault();
    const file = document.getElementById('file').files[0];
    const formData = new FormData();
    formData.append('file', file);

    fetch('http://127.0.0.1:8080/upload_file/', {
      method: 'POST',
      body: formData
    })
    .then(response => response.text())
    .then(text => alert(text))
    .catch(error => alert('File upload error: ' + error));
  });
</script>

</body>
</html>

注:不写script的部分也是可以执行的

将input的submit 换成button 的submit试着也可以执行,但是后端处理的路径不一样,所以后端处理代码有不同逻辑的路径切换

后端

URL配置路径

from django.contrib import admin
from django.urls import path
from Myapp.views import *
# from Myapp import views
urlpatterns = [
    path('admin/', admin.site.urls),
    path('upload_file/',upload_file),
  

]

 view后端接受逻辑

def upload_file(request):
    random_str = '123'
    myFile = request.FILES.get('file')
    print(myFile)
    file_name = random_str + '.' + str(myFile).split('.')[1]  # 'RESUMES/' +
    print(file_name)
    print(os.getcwd())
    if os.getcwd() == 'D:\django_test':  # 判断路径位置如果直接是D:\django_test\Myapp\RESUMES就不用切换路径了
        os.chdir('./Myapp/RESUMES')
        print(os.getcwd())
    os.system(r"touch {}".format(random_str + '.' + str(myFile).split('.')[1]))
    fp = open(file_name, 'wb+')
    print(fp)
    for i in myFile.chunks():
        print(i)
        fp.write(i)
    fp.close()
    return HttpResponse('')

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值