extjs 4,spring mvc 3アップロードファイル

6408 ワード

ここではextjs 4がspring mvc 3の注釈と組み合わせてアップロードファイルを完了した例について説明します.
1ページファイル
  

   




Click on "Browse"button (image) to select a file and click on Upload button


2 EXTjsのファイル
   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.');
                        }
                    });
                }
            }
        }]
    });
});
3ファイルをアップロードするbean
   

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


public class FileUploadBean {

	private CommonsMultipartFile file;

	public CommonsMultipartFile getFile() {
		return file;
	}

	public void setFile(CommonsMultipartFile file) {
		this.file = file;
	}
}

 

4 extjsに情報を表示させるためにbeanをもう1つ設計する

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+"}";
	}
}


ここは実は成功するかどうかを返します
5コントロール層
  

@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 extjs 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("-------------------------------------------");
		 if(uploadItem.getFile().getSize()>0){                   
		        try {    
		            SaveFileFromInputStream(uploadItem.getFile().getInputStream(),"D://",uploadItem.getFile().getOriginalFilename());    
		        } catch (IOException e) {    
		            System.out.println(e.getMessage());    
		            return null;    
		        }    
		    }    
		//set extjs return - sucsess
		extjsFormResult.setSuccess(true);
		
		return extjsFormResult.toString();
	}
	
	/* **       
	
	   * @param stream   
	   * @param path   
	   * @param filename   
	   * @throws IOException   
	   */   
	  public void SaveFileFromInputStream(InputStream stream,String path,String filename) throws IOException    
	  {          
	   FileOutputStream fs=new FileOutputStream(path + "/"+ filename);
	   byte[]  buffer=new byte[1024*1024];
	   int bytesum = 0;    
	      int byteread = 0; 
	        while ((byteread=stream.read())!=-1)
	        {
	        	bytesum+=byteread;
	        	
	        	  fs.write(buffer,0,byteread);    
	              fs.flush();    
	        	
	        }
	        fs.close();    
	        stream.close();    
	  }    


エラーが発生した場合、extjsFormResult.setSuccess(false);
return extjsFormResult.toString();
この2つの文は、フロントエンドext js処理に返されます.
最後にMVCの設定です
 

<!-- Activates various annotations to be detected in bean classes -->
    <context:annotation-config />

    <!-- Scans the classpath of this application for @Components to deploy as beans -->
    <context:component-scan base-package="com.loiane"/>

    <!-- Configures Spring MVC -->
    <import resource="mvc-config.xml"/>

    <!-- 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>

ファイルサイズ制限の設定
奇妙な問題は、ie 7では、少し問題があるようで、解決しなければならないが、firefoxとchromeでは問題ない.このextjsはおかしい.extを使わないで、普通のspring mvcでは問題ないよ.