前端
<!DOCTYPE html>
<html>
<body>
<h2>Upload File</h2>
<form action="http://127.0.0.1:5000/upload" 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>
后端
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())
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('')
标签:fp,文件,str,upload,Django,myFile,file,print,上传
From: https://blog.csdn.net/daxiashangxian/article/details/140087368