【问题标题】:Play an audio file from server django从服务器 django 播放音频文件
【发布时间】:2016-09-18 08:36:50
【问题描述】:

我打算使用 django 制作一个类似于应用程序的 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

索引.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:“charmap”编解码器无法解码位置 159 中的字节 0x90:字符映射到 我假设问题出在views.py中的fsock ...有人可以帮我解决这个问题吗? 谢谢

【问题讨论】:

    标签: ajax django


    【解决方案1】:

    您正在以读取模式打开文件,但该文件是二进制文件。 (请注意,您还以wb+ 模式写入文件)

    改变

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

    到

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

    另外,查看this so question 以设置Content-Type 和Content-Length

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-30
    • 2015-06-18
    • 1970-01-01
    • 2014-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多