Tôi đang sử dụng Khởi động mùa xuân và JS góc. Tôi có một trình điều khiển Spring REST mà tôi sử dụng để tải xuống một Tệp. khi tôi gọi nó bằng cách sử dụng http://localhost:8080/download nó hoạt động và tệp được tải xuống. Bây giờ tôi có một nút, khi tôi nhấp vào nó, tôi tập tin sẽ được tải xuống. vì vậy tôi đã viết một chức năng trong bộ điều khiển js góc của tôi để có được url của dịch vụ web mùa xuân của tôi nhưng khi tôi thử nghiệm nó không có gì xảy ra. Tôi nên làm gì để sửa lỗi này? Có cách nào tốt hơn để tải xuống tệp bằng Spring và Angular không?tải xuống tệp bằng Angular JS và dịch vụ web RESTful dựa trên Spring
/**
* 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();
}
tôi góc js chức năng (tôi đã thêm console.log ("ok") để xem nếu tôi nhận được một kết quả từ bộ điều khiển mùa xuân và nó in ok)
$scope.downloadFile = function() {
$http({method: 'GET', url: '/download'}).
success(function(result) {
console.log("ok");
}).
error(function(data, status, headers, config) {
console.log("oops");
});
};
và nút của tôi
<button class="btn btn-success" ng-click="downloadFile()">download</button>
Tôi không chắc liệu điều đó có hữu ích hay không, nhưng bạn có thể muốn kiểm tra điều này: http://stackoverflow.com/questions/17177303/spring-download-response-as-a-file –