rahul doshi rahul doshi - 1 year ago 122
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)
for chunk in f.chunks():
q = Files.objects.all()
return render(request, "index.html", {'q' : q})
def play_file(request) :
fsock = open(r'C:\Users\rdoshi\storage\%s' %file.file_name, 'r')
response = HttpResponse(fsock, content_type='audio/mpeg')
return response


<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
// e.preventDefault();
method: 'GET',
url: '/polls/play_file',
//data: {'id': 37},
success: function (recvd_file) {
//this gets called when server returns an OK response
var asd = '<audio id="myaudio" src="recvd_file.mp3" preload="auto"></audio>';
<table id='filetable' border = '1'>
{% for i in q %}
<button type="button" id='playlink' value = 'Download'>Download</button>
{% endfor %}
<form method = "post" action="../upload/" enctype ="multipart/form-data">{% csrf_token %}
<input type="file" name="files" multiple />
<input type = "submit" value="Upload" />

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?

Answer Source

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 )


fsock = open(r'C:\Users\rdoshi\storage\%s' %file.file_name, 'r')


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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download