1

I have an html. I need to upload image with other form fields in angularjs and spring rest service. Below is the html.

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular.js"></script>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular-route.js"></script>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular-resource.js"></script>
        <script type="text/javascript" src="resources/js/app.js"></script>
        <link href="resources/css/cards.css" rel="stylesheet" type="text/css" />
    </head>

    <body>

        <div ng-app="homeApp" ng-controller="homeController">
            <div>
                <div id="headerBarMenuText" href="#" ng-click="displayWeddingCards('weddingcards');">Wedding Cards</div>
                <div id="headerBarMenuText" href="#" ng-click="displayTab2('tab2');">Tab2</div>
                <div id="headerBarMenuText" href="#" ng-click="displayTab3('tab3');">Tab3</div>
                <div id="headerBarMenuText" href="#" ng-click="displayReturnGifts('returngifts');">Return Gifts</div>
                <div id="headerBarMenuText" href="#" ng-click="displayAdmin('admin');">Admin</div>
            </div>

            <div ng-show="showHome">
                Welcome. Please select the tabs for more details.
            </div>

            <div ng-show="admin">
                Admin
                <form>
                    <div>Name:</div>
                    <div>
                        <input type="text" ng-model="name" name="name" />
                    </div>
                    <div>Description:</div>
                    <div>
                        <input type="text" ng-model="description" name="description" />
                    </div>
                    <div>Category:</div>
                    <div>
                        <select ng-model="category" name="category">
                            <option value="0">None Selected</option>
                            <option value="1">Wedding Cards</option>
                            <option value="2">Tab 2</option>
                            <option value="3">Tab 3</option>
                            <option value="4">Return Gifts</option>
                        </select>
                    </div>
                    <div>Price:</div>
                    <div>
                        <input type="text" ng-model="price" name="price" />
                    </div>
                    <div>
                        <input type="file" file-model="multipartFile" name="multipartFile"></input>
                    </div>
                    <div>
                        <input type="button" value="Save" ng-click="uploadImage();" />
                    </div>
                </form>
            </div>
        </div>
    </body>
</html>

Below is the spring controller method.

@POST
@Path("/uploadImage")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public void uploadImage(){

}

In the above code, i want to upload the file along with data fields. I am using angular js and spring rest service. How can i send the file along with data in js and how can i get the values in spring controller. I mean what are the paramerters i should use in uploadImage() method to get form data fields and file in controller.

Adding controller class. And controller class.

@Controller
@Path("/cards")
public class AppController {

    @Autowired
    private AppService service;

    @RequestMapping(method = RequestMethod.POST, value = "uploadImage")
    public void uploadImage(@RequestParam("name") String name , 
    @RequestParam("file") MultipartFile file){
        System.out.println("Name: "+name);
        System.out.println("File Name: "+file.getOriginalFilename());
    }
}

Also adding js method.

$scope.uploadImage = function(){
    var fd = new FormData();
    fd.append('name', $scope.name);
    fd.append('description', $scope.description);
    fd.append('file', $scope.multipartFile);
    fd.append('price', $scope.price);
    $http.post('../oviyacards/service/cards/uploadImage',fd)
    .success(function(data) {
        alert("Success");
    }).error( function(data) {
        alert("Failure");
    });
}

And web.xml too.

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Oviya Cards</display-name>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring/Beans.xml</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <servlet>
        <servlet-name>cards-serlvet</servlet-name>
        <servlet-class>com.sun.jersey.spi.spring.container.servlet.SpringServlet</servlet-class>
        <init-param>
            <param-name>com.sun.jersey.config.property.packages</param-name>
            <param-value>com.oviya.cards.controller</param-value>
        </init-param>
        <init-param>
            <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
            <param-value>true</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>cards-serlvet</servlet-name>
        <url-pattern>/service/</url-pattern>
    </servlet-mapping>

    <welcome-file-list>
        <welcome-file>/WEB-INF/views/home.html</welcome-file>
    </welcome-file-list>

</web-app>

Please help me out. Thanks in advance.

Added pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.oviya</groupId>
  <artifactId>oviyacards</artifactId>
  <version>1</version>
  <packaging>war</packaging>

  <name>oviyacards</name>
  <url>http://maven.apache.org</url>

  <properties>
    <spring.version>3.2.5.RELEASE</spring.version>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <!-- https://mvnrepository.com/artifact/com.sun.jersey/jersey-client -->
    <dependency>
        <groupId>com.sun.jersey</groupId>
        <artifactId>jersey-client</artifactId>
        <version>1.19.1</version>
    </dependency>
    <!-- Spring 3 dependencies -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-dao</artifactId>
            <version>2.0.8</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-core</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

        <dependency>
            <groupId>net.sf.json-lib</groupId>
            <artifactId>json-lib</artifactId>
            <version>2.4</version>
            <classifier>jdk15</classifier>
        </dependency>

        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
            <version>2.5</version>
        </dependency>

        <!-- Jersey + Spring -->
        <dependency>
            <groupId>com.sun.jersey.contribs</groupId>
            <artifactId>jersey-spring</artifactId>
            <version>1.8</version>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework</groupId>
                    <artifactId>spring</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.springframework</groupId>
                    <artifactId>spring-core</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.springframework</groupId>
                    <artifactId>spring-web</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.springframework</groupId>
                    <artifactId>spring-beans</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.springframework</groupId>
                    <artifactId>spring-context</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-server</artifactId>
            <version>1.8</version>
        </dependency>
        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-json</artifactId>
            <version>1.8</version>
        </dependency>
        <dependency>
            <groupId>javax.ws.rs</groupId>
            <artifactId>jsr311-api</artifactId>
            <version>1.1.1</version>
        </dependency>
        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20131018</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.sun.jersey/jersey-bundle -->
        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-bundle</artifactId>
            <version>1.8-ea03</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.2.2</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.sun.jersey.contribs/jersey-multipart -->
        <dependency>
            <groupId>com.sun.jersey.contribs</groupId>
            <artifactId>jersey-multipart</artifactId>
            <version>1.19</version>
        </dependency>

  </dependencies>
  <build>
    <finalName>oviyacards</finalName>
  </build>
</project>
alexbt
  • 16,415
  • 6
  • 78
  • 87
Gopinath
  • 121
  • 1
  • 2
  • 10

1 Answers1

1

In your AngularJS controller, you could use something like this

function uploadImage(){
    var formData = new FormData();
    fd.append('file', multipartFile);
    fd.append('name', name);
    fd.append('description', description);
    fd.append('category', category);
    fd.append('price', price);
    $http.post("yourdomain.com/uploadImage", formData);
}

Please see the AngularJS documentation for $http:

Your REST controller could look similar to this

@RequestMapping(value = "/uploadImage", method = RequestMethod.POST)
public void uploadImage(@RequestParam("file") MultipartFile file,
    @RequestParam("name") String name, @RequestParam("description") String description, 
    @RequestParam("category") String category, @RequestParam("price") Double price){
    //process your image: file)
}
Leonard
  • 783
  • 3
  • 22
  • Why are you mixing JAX-RS Jersey annotations with Spring annotations? – Rana_S Jul 10 '17 at 12:39
  • Thanks for your answer. Here i want the form data as well. how can i get the form data in spring controller. Also could you please give me the full method for $http.post? – Gopinath Jul 10 '17 at 12:41
  • @RossiRobinsion: changed it – Leonard Jul 10 '17 at 12:44
  • @Rumo. Thanks. Here i also want to get the form data in spring controller. How could i get the form data? – Gopinath Jul 10 '17 at 12:45
  • @Gopinath: I changed the code accordingly. You can get the other data using the DTO. – Leonard Jul 10 '17 at 12:51
  • But in js we are not setting the form values. We are just setting the multipart file alone. Will this work? – Gopinath Jul 10 '17 at 12:55
  • Now i am getting below error. Jul 10, 2017 6:33:25 PM com.sun.jersey.spi.container.ContainerResponse mapMappableContainerException SEVERE: The RuntimeException could not be mapped to a response, re-throwing to the HTTP container java.lang.NullPointerException. It is going inside the method. And getting this error. – Gopinath Jul 10 '17 at 13:10
  • In formdataDTO object in uploadImages() method all the values are null. Could you please help me on this? @Rumo – Gopinath Jul 10 '17 at 13:45
  • I have one doubt here. In js, we are setting all the values. And we are setting multipartfile alone with key "file". But in uploadImage() method in controller, we are getting formDataDTO object using key "file". How all the values will come in 'file' keyword? – Gopinath Jul 10 '17 at 14:26
  • You're right. You have to use `@RequestBody` instead. Check if it works now. – Leonard Jul 11 '17 at 07:29
  • I changed it to @RequestBody. But now also I am getting null values in Controller. Below is the js code. $scope.uploadImage = function(){ var fd = new FormData(); fd.append('name', $scope.name); fd.append('description', $scope.description); fd.append('file', $scope.multipartFile); fd.append('price', $scope.price); $http.post('../oviyacards/service/cards/uploadImage',fd) .success(function(data) { alert("Success"); }).error( function(data) { alert("Failure"); }); } – Gopinath Jul 11 '17 at 07:52
  • try it without a dto (see above) – Leonard Jul 11 '17 at 09:42
  • Now i am getting error while deploying the application. Below is the error. SEVERE: The following errors and warnings have been detected with resource and/or provider classes: SEVERE: Missing dependency for method public void com.oviya.cards.controller.AppController.uploadImage(org.springframework.web.multip art.MultipartFile,java.lang.String,java.lang.String,java.lang.String,java.lang.Double) at parameter at index 0 The above error for all the parameters that we have in controller method. Please help me on this. Thank you. – Gopinath Jul 11 '17 at 10:34
  • pom.xml added . – Gopinath Jul 12 '17 at 07:34