ExtJS4 File Upload + Spring MVC 3實現文件上傳示例

碼頭工人 13年前發布 | 14K 次閱讀

這是一篇使用Ext JS 4 File Upload Field作為文件上傳前臺+Spring MVC 3作為服務器端接收文件。

This tutorial is also an update for the tutorial Ajax File Upload with ExtJS and Spring Framework, implemented with Ext JS 3 and Spring MVC 2.5.

 

Ext JS File Upload Form

First, we will need the Ext JS 4 File upload form. This one is the same as showed in Ext JS 4 docs

<PRE style="BACKGROUND-COLOR: #c5c5c5; FONT-WEIGHT: bold" class=javascript name="code">Ext.onReady(function(){

Ext.create('Ext.form.Panel', {
    title: 'File Uploader',
    width: 400,
    bodyPadding: 10,
    frame: true,
    renderTo: 'fi-form',
    items: [{
        xtype: 'filefield',
        name: 'file',
        fieldLabel: 'File',
        labelWidth: 50,
        msgTarget: 'side',
        allowBlank: false,
        anchor: '100%',
        buttonText: 'Select a File...'
    }],

    buttons: [{
        text: 'Upload',
        handler: function() {
            var form = this.up('form').getForm();
            if(form.isValid()){
                form.submit({
                    url: 'upload.action',
                    waitMsg: 'Uploading your file...',
                    success: function(fp, o) {
                        Ext.Msg.alert('Success', 'Your file has been uploaded.');
                    }
                });
            }
        }
    }]
});

});</PRE>

<DIV id=highlighter_655469 class="syntaxhighlighter ">

<DIV class=bar>HTML Page </DIV></DIV>

Then in the HTML page, we will have a div where we are going to render the Ext JS form. This page also contains the required javascript import

<PRE style="BACKGROUND-COLOR: #c5c5c5; FONT-WEIGHT: bold" class=html name="code"><html> <head> <title>Spring FileUpload Example with <a target="_blank" title="ExtJS" href="/misc/goto?guid=5033825256663260372">ExtJS</a> 4 Form</title>

<!-- <a target="_blank" title="Ext JS" href="/misc/goto?guid=5033825256663260372">Ext JS</a> Files -->
<link rel="stylesheet" type="text/css" href="/extjs4-file-upload-spring/<a target="_blank" title="extjs" href="/misc/goto?guid=5033825256663260372">extjs</a>/resources/css/ext-all.css" />
<script type="text/javascript" src="/extjs4-file-upload-spring/<a target="_blank" title="extjs" href="/misc/goto?guid=5033825256663260372">extjs</a>/bootstrap.js"></script>

<!-- file upload form -->
<script src="/extjs4-file-upload-spring/js/file-upload.js"></script>

</head> <body>

<p>Click on "Browse" button (image) to select a file and click on Upload button</p>

<div id="fi-form" style="padding:25px;"></div>

</body> </html></PRE>

<DIV id=highlighter_444187 class="syntaxhighlighter ">

<DIV class=bar>

<DIV class=toolbar>FileUpload Bean </DIV></DIV></DIV>

We will also need a FileUpload Bean to represent the file as a multipart file

<PRE style="BACKGROUND-COLOR: #c5c5c5; FONT-WEIGHT: bold" class=java name="code">package com.loiane.model;

import org.springframework.web.multipart.commons.CommonsMultipartFile;

/**

  • Represents file uploaded from <a target="_blank" title="extjs" href="/misc/goto?guid=5033825256663260372">extjs</a> form *
  • @author Loiane Groner
  • http://loiane.com
  • http://loianegroner.com */ public class FileUploadBean {

    private CommonsMultipartFile file;

    public CommonsMultipartFile getFile() {

     return file;
    

    }

    public void setFile(CommonsMultipartFile file) {

     this.file = file;
    

    } }</PRE> <DIV id=highlighter_761197 class="syntaxhighlighter "> <DIV class=bar> </DIV> <DIV class=bar>File Upload Controller </DIV></DIV>

    Then we will need a controller. This one is implemented with Spring MVC 3

    <PRE style="BACKGROUND-COLOR: #c5c5c5; FONT-WEIGHT: bold" class=java name="code">package com.loiane.controller;

import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.validation.ObjectError; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody;

import com.loiane.model.ExtJSFormResult; import com.loiane.model.FileUploadBean;

/**

  • Controller - Spring *
  • @author Loiane Groner
  • http://loiane.com
  • http://loianegroner.com */ @Controller @RequestMapping(value = "/upload.action") public class FileUploadController {

    @RequestMapping(method = RequestMethod.POST) public @ResponseBody String create(FileUploadBean uploadItem, BindingResult result){

     ExtJSFormResult extjsFormResult = new ExtJSFormResult();
    
     if (result.hasErrors()){
         for(ObjectError error : result.getAllErrors()){
             System.err.println("Error: " + error.getCode() +  " - " + error.getDefaultMessage());
         }
    
         //set <a target="_blank" title="extjs" href="/misc/goto?guid=5033825256663260372">extjs</a> return - error
         extjsFormResult.setSuccess(false);
    
         return extjsFormResult.toString();
     }
    
     // Some type of file processing...
     System.err.println("-------------------------------------------");
     System.err.println("Test upload: " + uploadItem.getFile().getOriginalFilename());
     System.err.println("-------------------------------------------");
    
     //set <a target="_blank" title="extjs" href="/misc/goto?guid=5033825256663260372">extjs</a> return - sucsess
     extjsFormResult.setSuccess(true);
    
     return extjsFormResult.toString();

}.</PRE>

<DIV id=highlighter_712618 class="syntaxhighlighter ">

<DIV class=bar> </DIV>

<DIV class=bar>Ext JS Form Return </DIV></DIV>

Some people asked me how to return something to the form to display a message to the user. We can implement a POJO with a success property. The success property is the only thing Ext JS needs as a return

<PRE style="BACKGROUND-COLOR: #c5c5c5; FONT-WEIGHT: bold" class=java name="code">package com.loiane.model;

/**

  • A simple return message for <a target="_blank" title="Ext JS" href="/misc/goto?guid=5033825256663260372">Ext JS</a> *
  • @author Loiane Groner
  • http://loiane.com
  • http://loianegroner.com */ public class ExtJSFormResult {

    private boolean success;

    public boolean isSuccess() {

     return success;
    

    } public void setSuccess(boolean success) {

     this.success = success;
    

    }

    public String toString(){

     return "{success:"+this.success+"}";
    

    } }</PRE> <DIV id=highlighter_811593 class="syntaxhighlighter "> <DIV class=bar>Spring Config </DIV></DIV>

    Don’t forget to add the multipart file config in the Spring config file

    <PRE style="BACKGROUND-COLOR: #c5c5c5; FONT-WEIGHT: bold" class=xml name="code"><!-- Configure the multipart resolver --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- one of the properties available; the maximum file size in bytes --> <property name="maxUploadSize" value="100000"/> </bean></PRE> <DIV id=highlighter_384908 class="syntaxhighlighter "> <DIV class=bar>NullPointerException </DIV></DIV>

    I also got some questions about NullPointerException. Make sure the fileupload field name has the same name as the CommonsMultipartFile property in the FileUploadBean class:

    ExtJS

    <PRE style="BACKGROUND-COLOR: #c5c5c5; FONT-WEIGHT: bold" class=javascript name="code">{ xtype: 'filefield', name: 'file', fieldLabel: 'File', labelWidth: 50, msgTarget: 'side', allowBlank: false, anchor: '100%', buttonText: 'Select a File...' }</PRE> <DIV id=highlighter_11942 class="syntaxhighlighter "> <DIV class=bar>Java:<PRE style="BACKGROUND-COLOR: #c5c5c5; FONT-WEIGHT: bold" class=java name="code">public class FileUploadBean {

    private CommonsMultipartFile file; } </PRE></DIV></DIV> <DIV id=highlighter_729887 class="syntaxhighlighter "> <DIV class=bar> </DIV> <DIV class=bar>These properties ALWAYS have to match!</DIV></DIV>

    You can still use the Spring MVC 2.5 code with the Ext JS 4 code presented in this tutorial.

    Download

    You can download the source code from my Github repository (you can clone the project or you can click on the download button on the upper right corner of the project page): https://github.com/loiane/extjs4-file-upload-spring

    You can also download the source code form the Google Code repository: http://code.google.com/p/extjs4-file-upload-spring/

    Both repositories have the same source. Google Code is just an alternative.

    Happy Coding! :)

 本文由用戶 碼頭工人 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!