我打算使用django创建一个类似app的dropbox。我可以实现将文件上传到服务器并在浏览器上显示。我希望用户能够下载或查看它。我正在尝试将其用于音频文件。我附上了views.py和index.html文件
from django.shortcuts import render
from django.http import HttpResponse
from django.shortcuts import render_to_response
from polls.models import Files
from os import walk
from os.path import isfile, join
def index(request):
return render(request,"index.html", {})
def upload(request):
for x in request.FILES.getlist("files"):
def process(f):
with open(r'C:\Users\rdoshi\storage\%s ' %f.name , 'wb+') as destination:
b = Files(file_name= f.name)
b.save()
for chunk in f.chunks():
destination.write(chunk)
process(x)
q = Files.objects.all()
return render(request, "index.html", {'q' : q})
def play_file(request) :
file=Files.objects.get(id=37)
fsock = open(r'C:\Users\rdoshi\storage\%s' %file.file_name, 'r')
response = HttpResponse(fsock, content_type='audio/mpeg')
return response
的index.html
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
//$("#playlink").click(function(e){
// e.preventDefault();
$.ajax({
method: 'GET',
url: '/polls/play_file',
//data: {'id': 37},
success: function (recvd_file) {
//this gets called when server returns an OK response
console.log("success");
var asd = '<audio id="myaudio" src="recvd_file.mp3" preload="auto"></audio>';
document.write(asd);
},
});
});
</script>
<table id='filetable' border = '1'>
{% for i in q %}
<tr>
<td>{{i.id}}</td>
<td>
{{i.file_name}}
<button type="button" id='playlink' value = 'Download'>Download</button>
</td>
</tr>
{% endfor %}
</table>
<form method = "post" action="../upload/" enctype ="multipart/form-data">{% csrf_token %}
<input type="file" name="files" multiple />
<input type = "submit" value="Upload" />
</form>
因此尝试播放该文件会给我这个错误
UnicodeDecodeError:&#39; charmap&#39;编解码器不能解码位置159中的字节0x90:字符映射到 我假设问题是在views.py中使用fsock ...有人可以帮我这个吗? 感谢
答案 0 :(得分:2)
You are opening the file in read mode, but the file is a binary file. ( Notice that you also write the file in wb+
mode )
change
fsock = open(r'C:\Users\rdoshi\storage\%s' %file.file_name, 'r')
to
fsock = open(r'C:\Users\rdoshi\storage\%s' %file.file_name, 'rb')
Also, have a look at this so question上的多项更改,以设置Content-Type
和Content-Length