Reputation: 11
I am new to Spring MVC and Angularjs , I am trying to do a file upload using Angularjs and spring MVC here is my html file:
When I start the tomcat server and try to run the application, I am getting 404 error ,resource is not available.Below is the url i use:
http://localhost:9090/Test/api/userfile/fileUploadForm
FileUpload.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>UserConfig FileUpload</title>
<script type="text/javascript">
// load angularjs specific version
var angularVersion = window.location.hash.substring(1);
if (angularVersion.indexOf('/') == 0) angularVersion =
angularVersion.substring(1);
document.write('<script type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/angularjs/' +
(angularVersion || '1.2.24') + '/angular.js"><\/script>');
</script>
<script type="text/javascript" src="siteConfig.js"></script>
</head>
<body>
<div ng-app="myApp" ng-controller = "SiteFileUploadCtrl">
<input type="file" file-model="myFile"/>
<button ng-click="uploadFile()">Upload</button>
</div>
</body>
</html>
siteConfig.js
var myApp = angular.module('myApp', []);
myApp.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]);
});
});
}
};
}]);
myApp.service('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function(file, uploadUrl){
var fd = new FormData();
fd.append('file', file);
$http.post(uploadUrl, fd, {
withCredentials : false,
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(){
console.log("success 1");
})
.error(function(){
console.log("error");
});
}
}]);
myApp.controller('SiteFileUploadCtrl', ['$scope', 'fileUpload',
function($scope, fileUpload){
$scope.uploadFile = function(){
alert("hi");
console.log("hello");
var file = $scope.myFile;
console.log('file is');
console.dir(file);
var uploadUrl = '/Test/login/api/userfile/upload';
fileUpload.uploadFileToUrl(file, uploadUrl);
};
}]);
Below is my Spring Controller code:
UploadController.java
package com.net.controller;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
@Controller
@RequestMapping("/api/userfile/")
public class UploadController {
@RequestMapping(value = "/fileUploadForm")
public ModelAndView getUploadForm() {
return new ModelAndView("FileUpload");
}
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public @ResponseBody String upload(
@RequestParam("file") MultipartFile file ) throws IOException {
String fileName = null;
if (!file.isEmpty()) {
try {
fileName = file.getOriginalFilename();
byte[] bytes = file.getBytes();
File newFile = new File("C:\\test\\" + fileName);
BufferedOutputStream buffStream =
new BufferedOutputStream(new FileOutputStream(newFile));
buffStream.write(bytes);
buffStream.close();
return "You have successfully uploaded " + fileName;
} catch (Exception e) {
return "You failed to upload " + fileName + ": " + e.getMessage();
}
} else {
return "Unable to upload. File is empty.";
}
}
}
Spring-context.xml full code:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<mvc:annotation-driven />
<context:component-scan base-package="com.net.controller" />
<mvc:resources mapping="/scripts/**" location="/scripts/" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/pages/</value>
</property>
<property name="suffix">
<value>.html</value>
</property>
</bean>
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />
</beans>
Below is my web.xml full code:
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>test</display-name>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/login/*</url-pattern>
</servlet-mapping>
</web-app>
The js files are placed under WEB-INF/scripts and the source html pages(FileUpload.html) are placed under WebContent/pages.
the spring-context.xml and web.xml are placed under the WEB-INF folder .The controller class is under com.net.controller
Now when I know I am doing some configuration and mapping wrong.I couldnt get that one.
Can anyone please point out the mapping mistake. Your help is really appreciated.
Thanks in Advance
Upvotes: 1
Views: 2014
Reputation: 3107
You have invalid api address like you submit upload file on /upload i.e if you site is running on localhost:8080
and upload url is localhost:8080/upload
.but you have create backend url is @RequestMapping("api/userfile/")
on controller and @RequestMapping(value = "/upload", method = RequestMethod.POST)
on method which mean your backend url is
api/userfile/upload
that why you getting 404 for that.You can change your angular url from /upload to /api/userfile/upload.it will be work for you.
Upvotes: 2