2015-04-05 73 views
0

我有一個簡單的彈簧控制器安裝程序通過AJAX請求返回文件(尤其是.CSV)。下面是它是運用YUI's骨架,製作標準XHR我的電話:彈簧控制器不返回文件

var downloadFile = Y.all('.downloadLink'); //traverses DOM for all downloadLink <a> tags 
    downloadFile.on(
     'click', 
     function(e){ 
      var fileName = e.currentTarget.attr('data-id');//retrieves file name 
      Y.io.request(
      '/download/' + fileName, 
      { 
       method: 'GET', 
       on: { 
        success: function(e) { 
         alert('success'); 
        }, 
        failure: function(e) { 
         alert(e.type); 
        } 
       } 
      }); 
    }); 

這裏是我的控制器:

@RequestMapping(method = RequestMethod.GET, value = "/download/{fileName:.+}") 
@ResponseBody 
public FileSystemResource download(@PathVariable String fileName) throws IOException { 
    File file = new File(rootPath + tempDir + '/' + fileName); 
    try { 
     if (file.exists()) { 
      logger.info(fileName + " downloaded"); 
      return new FileSystemResource(file); 
     } else { 
      logger.error("Could not download: " + fileName + " does not exist on server"); 
     } 
    } catch (Exception e) { 
     logger.error("Error Downloading File"); 
     e.printStackTrace(); 
    } 
    return null; 
} 

在本question建議,我試圖通過修改強制下載與

produces = MediaType.APPLICATION_OCTET_STREAM_VALUE 

的方法以及包括一個HttpeServletResponse和setti與

response.setContentType("application/force-download"); 

納克內容類型不設置的MediaType,我的要求是成功的,並且@ResponseBody我的文件的內容返回給瀏覽器。然而,當我包括我的MediaType收到406:

406 Not Acceptable: The resource identified by this request is only capable 
of generating responses with characteristics not acceptable according to the request "accept" headers. 

我搜索的文檔,但我還沒有發現其中「接受」,我應該使用參數,使之成爲一個有效的請求(如果單獨將甚至解決這個問題)。任何想法或建議的方法來檢索我的文件?歡呼隊友和復活節快樂

+0

你是如何提出請求?你需要在請求中設置Accept頭,如'Accept:application/octet-stream' – 2015-04-05 20:43:46

+0

好點,我將包括我的AJAX請求 – 2015-04-05 20:45:11

回答

2

當您提出請求時,您需要設置Accept標頭。從未使用YUI,但嘗試這樣的事情

 Y.io.request(
     '/download/' + fileName, 
     { 
      method: 'GET', 
      on: { 
       success: function(e) { 
        alert('success'); 
       }, 
       failure: function(e) { 
        alert(e.type); 
       } 
      }, 
      headers: {'Accept' : 'application/octet-stream'} 
     }); 
+0

謝謝@Predrag,'headers'確實是一個有效的iorequest屬性,但是這個集合返回相同的'406'錯誤,儘管這樣做非常有意義 – 2015-04-05 21:33:41

+0

我相信header屬性接受的唯一字符串是'*/*'', ''text/html'', ''application/json'',''text/javascript'', ''text/plain'', ''application/xml''和''text/xml''。來源http://alloyui.com/api/files/alloy-ui_src_aui-io_js_aui-io-request.js.html# – 2015-04-05 21:34:44

+0

我不希望任何客戶端框架來驗證您在標頭中發送的內容,因爲它是一個非常動態的區。無論如何,嘗試將其設置爲「*/*',看看它是否有任何區別。 – 2015-04-05 21:42:34