Posts Tagged “upload”

Finally found the way to do the uploading via Flex to a Java backend. What i have used is the Spring Web MVC framework by making use of the example in the Spring Documentation on the multipart support #. The documentation does not include some of the necessary configuration such as the web.xml setup plus the controller and servlet configuration. It is pretty standard if you understand Spring.

The cool part about Spring’s multipart support is that we can simply extract the multipart file from the command object. Any multipart content will be identified by the multipartResolver which we will configure following the documentation.

So all the tricky part is left to be done on the Spring controller. And with a bit of java.io knowledge, our upload can be easily done in two hours. Yes two hours… i realised my mistake in using the file upload example in Spring Web Flow when i was testing with the Flex frontend upload example. At first, i thought it would be cool to make use of it but i guess i have to “Keep it sweet and simple”. So the spring dispatcher servlet approach. I am in love with Spring.

(Updated)References:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
 public class ImageUploadController extends SimpleFormController {
 
	protected String fileUploadLocation;
 
	protected ModelAndView onSubmit(
	        HttpServletRequest request,
	        HttpServletResponse response,
	        Object command,
 
	        BindException errors) throws Exception {
 
	         // cast the bean - POJO
	        FileUploadBean bean = (FileUploadBean) command;
 
	        // let's see if there's content there
	        MultipartFile imageFile = bean.getFile();
 
	        //Check upload file
	        if (imageFile.getSize() == 0) {
	             //the user did not upload anything
			throw new Exception("No file uploaded");
	        }
	        //Get image filename
	        String fileName = imageFile.getOriginalFilename();
 
	        int index = fileName.toLowerCase().indexOf("jpg");
	        String fileName = "test.jpg";
 
	        //Create new File Object
	        String fileSeparator = System.getProperty("file.separator");
	        File newFile = new File(assetsLocation + fileSeparator + fileUploadLocation + fileSeparator + fileName);
 
	        //check for file
			if (newFile.exists()) {
			    try {
			        // Create file if it does not exist
			        boolean success = newFile.createNewFile();
			        if (success) {
			            	// File did not exist and was created
					System.out.println("File created");
			        } else {
			            // File already exists
					System.out.println("File not created");
			        }
			    } catch (IOException e) {
				// Handle your exception
			    }
			}
		    imageFile.transferTo(newFile);
	        return super.onSubmit(request, response, command, errors);
	    }
}

Web.Xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<servlet>
	<servlet-name>profileImageUpload</servlet-name>
	<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
	<servlet-name>profileImageUpload</servlet-name>
	<url-pattern>*.form</url-pattern>
</servlet-mapping>
 
imageUpload-servlet.xml
<pre lang="xml" line="1">
<?xml version="1.0" encoding="UTF-8"?>
 
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
	<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<!-- Limit uploads to small (5KB) files for this sample -->
		<property name="maxUploadSize" value="5120" />
	</bean>
 
	<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="location" value="/WEB-INF/test.properties"/>
	</bean>
	<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
        <property name="mappings">
            <props>
                <prop key="/upload.form">fileUploadController</prop>
            </props>
        </property>
    </bean>
 
    <bean id="fileUploadController" class="com.someclass.ImageUploadController">
        <property name="fileUploadLocation"><value>${fileuploadimage.location}</value></property>
        <property name="assetsLocation"><value>${fileuploadimage.assets}</value></property>
        <property name="commandClass"><value>com.someclass.FileUploadBean</value></property>
        <property name="successView"><value>confirmation.jsp</value></property>
    </bean>
</beans>

Flex codes with some modification from the example at http://blog.flexexamples.com/2007/09/21/uploading-files-in-flex-using-the-filereference-class/ (By request of Tamitutor)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
 
<?xml version="1.0" encoding="utf-8"?>
 
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
        layout="vertical"
        verticalAlign="middle"
        creationComplete="init();">
 
    <mx:Script>
        <![CDATA[
            [Bindable]
            private var fileRef:FileReference;
 
            private const FILE_UPLOAD_URL:String = "http://localhost:8080/demo/upload.form";
 
            private function init():void {
                fileRef = new FileReference();
                fileRef.addEventListener(Event.SELECT, fileRef_select);
                fileRef.addEventListener(ProgressEvent.PROGRESS, progressHandler);
                fileRef.addEventListener(Event.COMPLETE, fileRef_complete);
            }
 
            private function browseAndUpload():void {
                fileRef.browse();
                message.text = "";
            }
 
            private function fileRef_select(evt:Event):void {
                try {
                    message.text = "size (bytes): " + numberFormatter.format(fileRef.size);
                    var request:URLRequest = new URLRequest(FILE_UPLOAD_URL);
                    request.method = URLRequestMethod.POST;
                    var uploaderReqVars:URLVariables = new URLVariables("var=samevalue");
                    request.data = uploaderReqVars;
                    fileRef.upload(request, "file");
                } catch (err:Error) {
                    message.text = "ERROR: zero-byte file";
                }
            }
 
            private function fileRef_progress(evt:ProgressEvent):void {
                progressBar.setProgress(Number(evt.bytesLoaded), Number(evt.bytesTotal));
            }
 
            private function progressHandler(event:ProgressEvent):void {
            var file:FileReference = FileReference(event.target);
            progressBar.setProgress( Number(event.bytesLoaded), Number(event.bytesTotal));
        }
 
            private function fileRef_complete(evt:Event):void {
                message.text += " (complete)";
            }
        ]]>
    </mx:Script>
<mx:NumberFormatter id="numberFormatter" />
	<mx:ApplicationControlBar>
 
 
	    <mx:Button label="Upload file"
	            click="browseAndUpload();" />
	    <mx:Label id="message" />
	    <mx:ProgressBar id="progressBar" mode="manual"
	            visible="true" />
	</mx:ApplicationControlBar>
 
 
</mx:Application>

Comments Comments

Been searching around the web for examples to upload files via Flex. Flex, being a frontend engine and running on flash, does not have the capability to upload files on its own. It will still need a backend system to receive the file and place it in physical storage. Based on the examples i found, Flex is merely acting like a form data sender. However, there seems to be no examples for a backend system that receives from a Flex app. I am coding one right now but i think i will need to spend more time on security issues.

Examples

  • http://livedocs.adobe.com/flex/201/html/wwhelp/wwhimpl/common/html/wwhelp.htm?context=LiveDocs_Book_Parts&file=17_Networking_and_communications_173_6.html
  • http://blog.flexexamples.com/2007/09/21/uploading-files-in-flex-using-the-filereference-class

Comments Comments