2016-04-15 52 views
2

我需要上傳音頻文件到服務器並顯示服務器響應的圖像。我是新來的Java腳本和Ajax。我試圖從輸入標籤獲取音頻文件到ajax調用,但它返回非法調用。我需要將音頻文件上傳到java web服務,並將圖像作爲文件格式返回,因此需要將此圖像文件顯示爲預覽。有沒有辦法做到這一點?在此先感謝上傳音頻文件到服務器並設置服務器響應的圖像

<body> 
<form role="form" id="serviceReq" method="post" 
    enctype="multipart/form-data"> 
    Upload File : <input type="file" name="audio" 
     id="audioFile" title="Upload File"> 
    <button>Submit</button> 
</form> 
<div> 
    <!-- set Response image from server --> 
    <img alt="" id="preImage" src=""> 
</div> 

service.request.js

$(function() { 
var formName = "#serviceReq"; 
$(formName) 
     .on(
       'submit', 
       function(e) { 
        var documentData = new FormData(); 
        documentData.append('audio', $("#audioFile").prop(
          'files')[0]); 
        e.preventDefault(); 
        $.support.cors = true; 
        $ 
          .ajax({ 
           url : 'http://192.168.2.11:8082/SoundWaveService/audioWave/addAudioNew', 
           method : 'POST', 
           crossDomain : true, 
           contentType : 'multipart/form-data', 
           dataType : 'script', 
           data : documentData, 
           beforeSend : function() { 
           }, 
           success : function(data) { 
            /** 
            * set images to #preImage from server 
            * response 
            */ 
           }, 
           error : function(e) { 
            alert(e); 
           } 
          }); 
       });}); 

在Java中我的服務方法

@Path("/addAudioNew") 
@POST 
@Produces(MediaType.APPLICATION_OCTET_STREAM) 
@Consumes(MediaType.MULTIPART_FORM_DATA) 
public Response insertAudioWaveNew(@FormDataParam("audio") InputStream audioFile) throws Exception { 
    File response = null; 
    response = fetchService.insertAudioNew(audioFile); 
    return Response.ok(response, MediaType.APPLICATION_OCTET_STREAM) 
      .header("Content-Disposition", "attachement; filename=\"" + response.getName() + "\"").build(); 
} 

回答

1

請試試這個:

$(function() { 
var formName = "#serviceReq"; 
$(formName).on('submit', function(e) { 
    e.preventDefault(); 

    var documentData = new FormData(); 
    documentData.append('audio', $("#audioFile")[0].files[0]); 
    $.support.cors = true; 

    $.ajax({ 
     url : 'http://192.168.2.11:8082/SoundWaveService/audioWave/addAudioNew', 
     method : 'POST', 
     crossDomain : true, 
     contentType : 'multipart/form-data', 
     processData: false, //New 
     data : documentData, 
     beforeSend : function() { }, 
     success : function(data) { 
      /** 
      * set images to #preImage from server 
      * response 
      */ 
     }, 
     error : function(e) { 
      alert(e); 
     } 
    }); 
}); 
}); 

如果您使用跨域ajax請求,您的服務器必須將Access-Control-Allow-Origin: *添加到響應標頭。

相關問題