У меня есть страница, где пользователь может загружать изображение. Я отправляю данные на url, используя запрос по запросу угловых js. Мое сомнение в том, как получить эти данные в сервлет. Я хочу сохранить изображение в базе данных. Пожалуйста, дайте мне знать, если это правильный подход для выполнения этой деятельности
//Controller
app.controller('myCtrl', ['$scope', 'fileUpload', function($scope, fileUpload){
$scope.uploadFile = function(){
var file = $scope.myFile;
console.log('file is ' + (file));
var uploadUrl = "/Angular/login";
fileUpload.uploadFileToUrl(file, uploadUrl);
};
}]);
//Service
app.service('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function(file, uploadUrl){
var fd = new FormData();
fd.append('file', file);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(){
})
.error(function(){
});
}
}]);
//directive
app.directive('fileModel', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
element.bind('change', function(){
scope.$apply(function(){
modelSetter(scope, element[0].files[0]);
});
});
}
};
}]);
Как я могу получить вышеуказанные данные в Java-сервлете?
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
Вы можете безопасно использовать Apache Commons FileUpload для этого, который также будет работать со старыми версиями сервлета.
Проверьте http://commons.apache.org/proper/commons-fileupload/using.html
<!DOCTYPE html>
<html ng-app="FileuploadApp">
<head>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<script>
angular
.module("FileuploadApp", [])
.controller("FileCtrl", function($scope, $http) {
$scope.upload = function() {
var fd = new FormData();
fd.append("file", $scope.file);
$http({
withCredentials: true,
method: 'POST',
url: './fileupload',
data: fd,
headers: { 'Content-Type': undefined },
transformRequest: angular.identity
});
}
})
.directive('fileModel', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
element.bind('change', function(){
scope.$apply(function(){
modelSetter(scope, element[0].files[0]);
});
});
}
};
}]);
</script>
</head>
<body ng-controller="FileCtrl">
<input type="file" file-model="file"/>
<input type="button" value="Upload!" ng-click="upload();">
</body>
</html>
@WebServlet(urlPatterns="/fileupload")
public class FileuploadTestServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
if (ServletFileUpload.isMultipartContent(req)) {
try {
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletContext servletContext = this.getServletConfig().getServletContext();
File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
factory.setRepository(repository);
ServletFileUpload fileUpload = new ServletFileUpload(factory);
List<FileItem> files = fileUpload.parseRequest(req);
if (files != null && !files.isEmpty()) {
for (FileItem item : files) {
System.out.println("* " + item.getName() + " " + item.getSize() + " bytes.");
}
}
} catch (FileUploadException e) {
e.printStackTrace();
}
}
}
}
* cthulhu.bin 42 bytes.
Вы можете использовать InputStream stream = request.getInputStream();
читать необработанные данные из запроса сервлета