我正在使用 Spring boot 和 Angular JS 。我有一个用于下载文件的 Spring REST 控制器。当我使用http://localhost:8080/download调用它时,它可以工作并下载文件。现在我有一个按钮,当我点击它时,我将下载文件。所以我在我的 Angular js 控制器中编写了一个函数来获取我的 Spring Web 服务的 url,但是当我测试它时什么也没发生。我该怎么做才能解决这个问题?有没有更好的方法来使用 Spring 和 Angular 下载文件?
/**
* Size of a byte buffer to read/write file
*/
private static final int BUFFER_SIZE = 4096;
private String filePath = "C:\\Users\\marwa\\Desktop\\marwa\\gg.jpg";
/**
* Method for handling file download request from client
*/
@RequestMapping (value="/download", method=RequestMethod.GET )
public void doDownload(HttpServletRequest request,
HttpServletResponse response) throws IOException {
// get absolute path of the application
ServletContext context = request.getServletContext();
String appPath = context.getRealPath("");
System.out.println("filepath = " + filePath);
// construct the complete absolute path of the file
File downloadFile = new File(filePath);
FileInputStream inputStream = new FileInputStream(downloadFile);
// get MIME type of the file
String mimeType = context.getMimeType(filePath);
if (mimeType == null) {
// set to binary type if MIME mapping not found
mimeType = "application/octet-stream";
}
System.out.println("MIME type: " + mimeType);
// set content attributes for the response
response.setContentType(mimeType);
response.setContentLength((int) downloadFile.length());
// set headers for the response
String headerKey = "Content-Disposition";
String headerValue = String.format("attachment; filename=\"%s\"",
downloadFile.getName());
response.setHeader(headerKey, headerValue);
// get output stream of the response
OutputStream outStream = response.getOutputStream();
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead = -1;
// write bytes read from the input stream into the output stream
while ((bytesRead = inputStream.read(buffer)) != -1) {
outStream.write(buffer, 0, bytesRead);
}
inputStream.close();
outStream.close();
}
我的 Angular js 函数(我添加了 console.log("ok") 以查看我是否从 spring 控制器获得结果并且打印正常)
$scope.downloadFile = function () {
$http({method: 'GET', url: '/download'}).
success(function(result) {
console.log("ok");
}).
error(function(data, status, headers, config) {
console.log("oops");
});
};
和我的按钮
<button class="btn btn-success" ng-click="downloadFile()">download</button>