我試圖讓Django上傳一個文件(保持簡單,現在),但我有困難。這是所有相關的代碼(我知道的)。也許我的settings.py有問題?我的代碼是Stack Overflow上的各種答案。我已經檢查過here。在Django中上傳文件
當我選擇一個文件(〜8.5MB的文件,因爲我看到Django的做一些有趣的事情,如果它是在2.5MB),然後按提交,我帶到上傳成功頁面,但似乎無法找到我在我的項目目錄中的任何地方
我使用Apache運行的開發runserver服務圖像。
settings.py
MEDIA_ROOT = '/Users/adam/Documents/workspace/sitename/media'
MEDIA_URL = 'http://127.0.0.1:8000/media/'
STATIC_ROOT = '/Library/WebServer/Documents/static/'
STATIC_URL = 'http://10.0.1.15/static/'
ADMIN_MEDIA_PREFIX = '/media/admin/'
STATICFILES_DIRS = (
)
*靜態URL是我的本地Apache網絡服務器的地址。
urls.py
urlpatterns = patterns('',
('^$', index),
('^uploadfile/$', uploadfile),
('^uploadsuccess/$', uploadsuccess),
)
if settings.DEBUG:
from django.views.static import serve
_media_url = settings.MEDIA_URL
if _media_url.startswith('/'):
_media_url = _media_url[1:]
urlpatterns += patterns('',
(r'^%s(?P<path>.*)$' % _media_url,
serve,
{'document_root': settings.MEDIA_ROOT}))
del(_media_url, serve)
views.py
def uploadsuccess(request):
return render_to_response('uploadsuccess.html', {})
class UploadFileForm(forms.Form):
file = forms.FileField()
def uploadfile(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
handle_uploads(request.FILES['file'])
form.save()
return HttpResponseRedirect('/')
else:
form = UploadFileForm()
return render_to_response('fileupload.html', {'form': form}, context_instance=RequestContext(request))
def handle_uploads(file):
logging.debug("upload_here")
if file:
destination = open('/tmp/'+file.name, 'wb+')
for chunk in file.chunks():
destination.write(chunk)
destination.close()
fileupload.html
<html>
<body>
<h1>Upload a file</h1>
<form enctype="multipart/form-data" method="post" action="/uploadsuccess/">
{% csrf_token %}
<table>
{% for field in form %}
{{ field.label_tag }}
{{ field }}
{% endfor %}
</table>
<input type="submit" value="Submit" id="Save"/>
</form>
<body>
</html>
uploadsuccess.html
<html>
<body>
<h1>Upload Successful!</h1>
<body>
</html>
只是爲了驗證,你有沒有嘗試在「/tmp/'+file.name尋找它,我之所以問是因爲你說你無法在你的項目中找到它的任何地方,並從我所看到的目標不在你的項目dir – Paulo 2011-06-02 18:22:41
這是我的一個問題,謝謝!我的印象是/ tmp /在我的項目文件夾中不在根目錄中。 – Adam 2011-06-02 20:57:39