rahul doshi rahul doshi - 2 months ago 25
Ajax Question

Play an audio file from server django

I am planning to make a dropbox like app using django.I could achieve uploading file into server and showing it on the browser.I want users to be able to download or view it.I am trying it for an audio file initially.Ive attached my views.py and index.html file

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>


So trying to play the file gives me this error

UnicodeDecodeError: 'charmap' codec can't decode byte 0x90 in position 159: character maps to
I am assuming problem is with fsock in views.py...could someone help me with this?
Thanks

Answer

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 to set Content-Type and Content-Length

Comments