Я использую Spring boot и Angular JS. У меня есть контроллер Spring REST, который я использую для загрузки файла. когда я вызываю его с помощью http://localhost:8080/download, он работает, и файл загружается. Теперь у меня есть кнопка, когда я нажимаю на нее, я скачиваю файл. поэтому я написал функцию в своем контроллере angular js, чтобы получить URL-адрес моей веб-службы Spring, но когда я ее протестировал, ничего не произошло. что мне делать, чтобы это исправить? Есть ли лучший способ загрузки файлов с помощью 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>