2016-09-18 92 views
0

我打算使用django製作一個類似於app的Dropbox。我可以實現將文件上傳到服務器並在瀏覽器上顯示它。我希望用戶能夠下載或查看它。我是嘗試它的音頻文件initially.Ive附上了我的views.py和index.html文件從服務器播放音頻文件django

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> 

所以試圖播放的文件給了我這個錯誤

統一codeDecodeError:'charmap'編解碼器無法解碼位置159中的字節0x90:字符映射到 我假設問題與views.py中的fsock ...有人可以幫助我嗎? 謝謝

回答

2

您正在以讀取模式打開文件,但文件是二進制文件。 (請注意,您也寫在文件中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-TypeContent-Length

+0

是的,這確實它....你也可以告訴在index.html的成功方法ajax的src中添加什麼? –

+0

那麼,你必須把base64音頻二進制數據放到src中 - 看看[html5 media和data uri#Audio Section](https://www.iandevlin.com/blog/2012/09/html5/html5-media-and-data-uri)以及[this so answer](http://stackoverflow.com/questions/12467922/setting-html5-media-source-using-ajax) – algrebe

+0

那麼你解決了我的大部分問題....萬分感謝! –