`
fengzgxing
  • 浏览: 242858 次
  • 性别: Icon_minigender_1
  • 来自: 四川
社区版块
存档分类
最新评论

flex + Struts2 文件上传

    博客分类:
  • Java
阅读更多
欢迎 fengzgxing 收件箱 我的应用 我的订阅

我的参与

我的闲聊

我的圈子

我的收藏
我的博客 设置 退出 
问答首页 → 问答分类: Java编程和Java企业应用 → Struts → flex前端如何上传文件到Struts2 ...
flex前端如何上传文件到Struts2的action中?
悬赏:5 发布时间:2009-04-15 提问人:mikeyzhou (初级程序员)
前言:
我在flex问答部分发了提问,但是前思后想还是觉得问题根本在struts2这里,下面附上我的代码和问题
fileupload.mxml
Xml代码
<?xml version="1.0" encoding="utf-8"?>    
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" xmlns="*" creationComplete="init();">    
<mx:Script>    
<![CDATA[   
    import flash.net.FileReference;   
    import mx.controls.Alert;   
    import mx.events.CloseEvent;   
    import flash.events.*;   
      
    private var file:FileReference;   
      
    private function init(): void{   
        Security.allowDomain("*"); 
        file = new FileReference(); 
        file.addEventListener(ProgressEvent.PROGRESS, onProgress);   
        file.addEventListener(Event.SELECT, onSelect);   
        file.addEventListener(Event.COMPLETE, completeHandle);   
    } 
      
    private function completeHandle(event:Event):void{   
        Alert.show("恭喜你,上传成功");   
    } 
      
    private function upload(): void{ 
        var noFilter:FileFilter = new FileFilter("All(*.*)", "*.*"); 
        var imagesFilter:FileFilter = new FileFilter("Images (*.jpg, *.jpeg, *.png)", "*.jpg;*.jpeg;*.png"); 
        var docFilter:FileFilter = new FileFilter("Documents(*.pdf,*.doc,*.txt)", "*.pdf;*.doc;*.txt");   
        //var allTypes:Array = new Array(imageTypes);   
        file.browse([noFilter,imagesFilter, docFilter]);  
        //file.browse();   
    } 
    private function onSelect(e: Event): void{   
        Alert.show("上传 " + file.name + " (共 "+Math.round(file.size)+" 字节)?",   
                    "确认上传",   
                    Alert.YES|Alert.NO,   
                    null,   
                    proceedWithUpload);   
    } 
      
    private function onProgress(e: ProgressEvent): void{ 
        lbProgress.text = " 已上传 " + e.bytesLoaded+ " 字节,共 " + e.bytesTotal + " 字节";   
        var proc: uint = e.bytesLoaded / e.bytesTotal * 100;   
        bar.setProgress(proc, 100);   
        bar.label= "当前进度: " + " " + proc + "%";   
    } 
      
    private function proceedWithUpload(e: CloseEvent): void{   
        if (e.detail == Alert.YES){   
            //var request: URLRequest = new URLRequest("http://localhost:8080/upload/fileUpload"); 
            //var request: URLRequest = new URLRequest("http://localhost:8080/uploadstruts1/fileUpload.do"); 
            var request: URLRequest = new URLRequest("http://localhost:8080/MyTianHuiWeb3.0/fileUpload.th"); 
            try { 
                file.upload(request); 
            } catch (error:Error) {   
                trace("上传失败");   
            } 
        } 
    }   
]]>    
</mx:Script>    
    
<mx:Canvas width="100%" height="100%" x="10" y="170" fontSize="15">    
<mx:VBox width="100%" horizontalAlign="center">    
<mx:Label id="lbProgress" text="上传"/>    
<mx:ProgressBar id="bar" labelPlacement="bottom" themeColor="#F20D7A"    
minimum="0" visible="true" maximum="100" label="当前进度: 0%"    
direction="right" mode="manual" width="200"/>    
 
<mx:Button label="上传文件" click="upload();"/>    
</mx:VBox>    
</mx:Canvas>    
</mx:Application>   

<?xml version="1.0" encoding="utf-8"?> 
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" xmlns="*" creationComplete="init();"> 
<mx:Script> 
<![CDATA[ 
import flash.net.FileReference; 
import mx.controls.Alert; 
import mx.events.CloseEvent; 
import flash.events.*; 

private var file:FileReference; 

private function init(): void{ 
Security.allowDomain("*");
file = new FileReference();
file.addEventListener(ProgressEvent.PROGRESS, onProgress); 
file.addEventListener(Event.SELECT, onSelect); 
file.addEventListener(Event.COMPLETE, completeHandle); 
}

private function completeHandle(event:Event):void{ 
    Alert.show("恭喜你,上传成功"); 
}

private function upload(): void{
var noFilter:FileFilter = new FileFilter("All(*.*)", "*.*");
var imagesFilter:FileFilter = new FileFilter("Images (*.jpg, *.jpeg, *.png)", "*.jpg;*.jpeg;*.png");
var docFilter:FileFilter = new FileFilter("Documents(*.pdf,*.doc,*.txt)", "*.pdf;*.doc;*.txt"); 
//var allTypes:Array = new Array(imageTypes); 
file.browse([noFilter,imagesFilter, docFilter]);
//file.browse(); 
}
private function onSelect(e: Event): void{ 
Alert.show("上传 " + file.name + " (共 "+Math.round(file.size)+" 字节)?", 
"确认上传", 
Alert.YES|Alert.NO, 
null, 
proceedWithUpload); 
}

private function onProgress(e: ProgressEvent): void{
lbProgress.text = " 已上传 " + e.bytesLoaded+ " 字节,共 " + e.bytesTotal + " 字节"; 
var proc: uint = e.bytesLoaded / e.bytesTotal * 100; 
bar.setProgress(proc, 100); 
bar.label= "当前进度: " + " " + proc + "%"; 
}

private function proceedWithUpload(e: CloseEvent): void{ 
if (e.detail == Alert.YES){ 
//var request: URLRequest = new URLRequest("http://localhost:8080/upload/fileUpload");
//var request: URLRequest = new URLRequest("http://localhost:8080/uploadstruts1/fileUpload.do");
var request: URLRequest = new URLRequest("http://localhost:8080/MyTianHuiWeb3.0/fileUpload.th");
try {
file.upload(request);
} catch (error:Error) { 
trace("上传失败"); 
}
}

]]> 
</mx:Script> 
 
<mx:Canvas width="100%" height="100%" x="10" y="170" fontSize="15"> 
<mx:VBox width="100%" horizontalAlign="center"> 
<mx:Label id="lbProgress" text="上传"/> 
<mx:ProgressBar id="bar" labelPlacement="bottom" themeColor="#F20D7A" 
minimum="0" visible="true" maximum="100" label="当前进度: 0%" 
direction="right" mode="manual" width="200"/> 

<mx:Button label="上传文件" click="upload();"/> 
</mx:VBox> 
</mx:Canvas> 
</mx:Application> 


struts.xml
Xml代码
<package name="uploadInterceptor" extends="struts-default" namespace=""> 
    <interceptors> 
        <interceptor-stack name="uploadstack"> 
            <interceptor-ref name="exception"/> 
            <interceptor-ref name="alias"/> 
            <interceptor-ref name="servletConfig"/> 
            <interceptor-ref name="prepare"/> 
            <interceptor-ref name="i18n"/> 
            <interceptor-ref name="chain"/> 
            <interceptor-ref name="debugging"/> 
            <interceptor-ref name="profiling"/> 
            <interceptor-ref name="scopedModelDriven"/> 
            <interceptor-ref name="modelDriven"/> 
            <!--  
            <interceptor-ref name="fileUpload"/> 
             --> 
            <interceptor-ref name="checkbox"/> 
            <interceptor-ref name="staticParams"/> 
            <interceptor-ref name="params"> 
              <param name="excludeParams">dojo\..*</param> 
            </interceptor-ref> 
            <interceptor-ref name="conversionError"/> 
            <interceptor-ref name="validation"> 
                <param name="excludeMethods">input,back,cancel,browse</param> 
            </interceptor-ref> 
            <interceptor-ref name="workflow"> 
                <param name="excludeMethods">input,back,cancel,browse</param> 
            </interceptor-ref> 
        </interceptor-stack> 
    </interceptors> 
</package> 
 
<package name="uploadPackage" extends="uploadInterceptor" namespace="" > 
    <action name="fileUpload" class="fileUploadAction2" method="fileUpload"/> 
</package> 

<package name="uploadInterceptor" extends="struts-default" namespace="">
<interceptors>
<interceptor-stack name="uploadstack">
    <interceptor-ref name="exception"/>
    <interceptor-ref name="alias"/>
    <interceptor-ref name="servletConfig"/>
    <interceptor-ref name="prepare"/>
    <interceptor-ref name="i18n"/>
    <interceptor-ref name="chain"/>
    <interceptor-ref name="debugging"/>
    <interceptor-ref name="profiling"/>
    <interceptor-ref name="scopedModelDriven"/>
    <interceptor-ref name="modelDriven"/>
    <!--
    <interceptor-ref name="fileUpload"/>
     -->
    <interceptor-ref name="checkbox"/>
    <interceptor-ref name="staticParams"/>
    <interceptor-ref name="params">
      <param name="excludeParams">dojo\..*</param>
    </interceptor-ref>
    <interceptor-ref name="conversionError"/>
    <interceptor-ref name="validation">
        <param name="excludeMethods">input,back,cancel,browse</param>
    </interceptor-ref>
    <interceptor-ref name="workflow">
        <param name="excludeMethods">input,back,cancel,browse</param>
    </interceptor-ref>
</interceptor-stack>
</interceptors>
</package>

<package name="uploadPackage" extends="uploadInterceptor" namespace="" >
<action name="fileUpload" class="fileUploadAction2" method="fileUpload"/>
</package>


spring-action.xml
Xml代码
<bean id="fileUploadAction2" class="com.FileUploadAction2" scope="request"/> 

<bean id="fileUploadAction2" class="com.FileUploadAction2" scope="request"/>


FileUploadAction2.java
Java代码
import java.io.File;  
import java.util.Iterator;  
import java.util.List;  
 
import javax.servlet.http.HttpServletRequest;  
 
import org.apache.commons.fileupload.FileItem;  
import org.apache.commons.fileupload.FileUploadException;  
import org.apache.commons.fileupload.disk.DiskFileItemFactory;  
import org.apache.commons.fileupload.servlet.ServletFileUpload;  
import org.apache.struts2.ServletActionContext;  
 
public class FileUploadAction2 {  
    public void fileUpload() {  
          
        System.out.println("Access !");  
          
        HttpServletRequest request = ServletActionContext.getRequest();  
          
        System.out.println(request.toString());  
          
        // 定义文件的上传路径  
        String uploadPath = "C:\\";  
        // 限制文件的上传大小  
        int maxPostSize = 100 * 1024 * 1024;  
          
        //保存文件到服务器中  
        DiskFileItemFactory factory = new DiskFileItemFactory();  
        factory.setSizeThreshold(4096);  
        ServletFileUpload upload = new ServletFileUpload(factory);  
        upload.setSizeMax(maxPostSize);  
        try {  
            List fileItems = upload.parseRequest(request);  
            Iterator iter = fileItems.iterator();  
            while (iter.hasNext()) {  
                FileItem item = (FileItem) iter.next();  
                if (!item.isFormField()) {  
                    String name = item.getName();  
                    System.out.println(name);  
                    try {  
                        item.write(new File(uploadPath + name));  
                    } catch (Exception e) {  
                        e.printStackTrace();  
                    }  
                }  
            }  
        } catch (FileUploadException e) {  
            e.printStackTrace();  
            System.out.println(e.getMessage() + "结束");  
        }  
    }  


import java.io.File;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.struts2.ServletActionContext;

public class FileUploadAction2 {
public void fileUpload() {

System.out.println("Access !");

HttpServletRequest request = ServletActionContext.getRequest();

System.out.println(request.toString());

// 定义文件的上传路径
String uploadPath = "C:\\";
// 限制文件的上传大小
int maxPostSize = 100 * 1024 * 1024;

        //保存文件到服务器中
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(4096);
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(maxPostSize);
        try {
            List fileItems = upload.parseRequest(request);
            Iterator iter = fileItems.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                if (!item.isFormField()) {
                    String name = item.getName();
                    System.out.println(name);
                    try {
                        item.write(new File(uploadPath + name));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
            System.out.println(e.getMessage() + "结束");
        }
}
}


---------------------------------------------------------------------------------------------
描述:
我在web+servlet里面可以正常上传
我在struts1.2 action里面也可以正常上传
只需要修改一下URLRequest的指向,将fileupload.mxml编译成flash就可以进行上述2个的测试。
但是我在struts2 action里面的fileUpload方法里却得不到文件(公司项目)!
因为不知如何将flex上传的Flie和struts2的action进行绑定(是否能直接使用Struts2的fileUpload拦截器拦截文件),所以还是沿用struts1的方式写的方法,并修改了action的拦截器设置,去掉了fileUpload拦截器(不知道这样改对不对),但是依然取不到文件。
问题:
不知道如何才能在struts2的action里才能取到flex上传的文件呢???
ps:不知道怎么才能知道request里是不是有文件流?是request的某个方法吗?上面打出了request信息"org.apache.struts2.dispatcher.multipart.MultiPartRequestWrapper@173089d"但我不知道时候包含了文件……
问题补充:
我把配置改成了这样
Xml代码
<package name="uploadPackage" extends="struts-default" namespace="" >   
        <interceptors> 
            <interceptor-stack name="uploadstack"> 
                <interceptor-ref name="exception"/> 
                <interceptor-ref name="alias"/> 
                <interceptor-ref name="servletConfig"/> 
                <interceptor-ref name="prepare"/> 
                <interceptor-ref name="i18n"/> 
                <interceptor-ref name="chain"/> 
                <interceptor-ref name="debugging"/> 
                <interceptor-ref name="profiling"/> 
                <interceptor-ref name="scopedModelDriven"/> 
                <interceptor-ref name="modelDriven"/> 
                <!--  
                <interceptor-ref name="fileUpload"/> 
                 --> 
                <interceptor-ref name="checkbox"/> 
                <interceptor-ref name="staticParams"/> 
                <interceptor-ref name="params"> 
                  <param name="excludeParams">dojo\..*</param> 
                </interceptor-ref> 
                <interceptor-ref name="conversionError"/> 
                <interceptor-ref name="validation"> 
                    <param name="excludeMethods">input,back,cancel,browse</param> 
                </interceptor-ref> 
                <interceptor-ref name="workflow"> 
                    <param name="excludeMethods">input,back,cancel,browse</param> 
                </interceptor-ref> 
            </interceptor-stack> 
        </interceptors> 
        <action name="fileUpload" class="fileUploadAction2" method="fileUpload"> 
            <interceptor-ref name="uploadstack"/> 
        </action> 
    </package> 

<package name="uploadPackage" extends="struts-default" namespace="" >
     <interceptors>
<interceptor-stack name="uploadstack">
    <interceptor-ref name="exception"/>
    <interceptor-ref name="alias"/>
    <interceptor-ref name="servletConfig"/>
    <interceptor-ref name="prepare"/>
    <interceptor-ref name="i18n"/>
    <interceptor-ref name="chain"/>
    <interceptor-ref name="debugging"/>
    <interceptor-ref name="profiling"/>
    <interceptor-ref name="scopedModelDriven"/>
    <interceptor-ref name="modelDriven"/>
    <!--
    <interceptor-ref name="fileUpload"/>
     -->
    <interceptor-ref name="checkbox"/>
    <interceptor-ref name="staticParams"/>
    <interceptor-ref name="params">
      <param name="excludeParams">dojo\..*</param>
    </interceptor-ref>
    <interceptor-ref name="conversionError"/>
    <interceptor-ref name="validation">
        <param name="excludeMethods">input,back,cancel,browse</param>
    </interceptor-ref>
    <interceptor-ref name="workflow">
        <param name="excludeMethods">input,back,cancel,browse</param>
    </interceptor-ref>
</interceptor-stack>
</interceptors>
<action name="fileUpload" class="fileUploadAction2" method="fileUpload">
<interceptor-ref name="uploadstack"/>
</action>
  </package>

还是不行啊
问题补充:
目前的解决办法:
之前的web.mxl
Xml代码
    <filter>    
    <filter-name>struts2</filter-name>    
    <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>    
    <init-param>    
        <param-name>config</param-name>    
        <param-value>struts-default.xml,struts-plugin.xml,../conf/struts.xml</param-value>    
    </init-param>    
</filter>    
<filter-mapping>    
    <filter-name>struts2</filter-name>    
    <url-pattern>/*</url-pattern>    
</filter-mapping>   

        <filter> 
        <filter-name>struts2</filter-name> 
        <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class> 
        <init-param> 
            <param-name>config</param-name> 
            <param-value>struts-default.xml,struts-plugin.xml,../conf/struts.xml</param-value> 
        </init-param> 
    </filter> 
    <filter-mapping> 
        <filter-name>struts2</filter-name> 
        <url-pattern>/*</url-pattern> 
    </filter-mapping> 


修改为
Xml代码
<filter>    
        <filter-name>struts2</filter-name>    
        <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>    
        <init-param>    
            <param-name>config</param-name>    
            <param-value>struts-default.xml,struts-plugin.xml,../conf/struts.xml</param-value>    
        </init-param>    
    </filter>    
    <filter-mapping>    
        <filter-name>struts2</filter-name>    
        <url-pattern>*.th</url-pattern>    
    </filter-mapping>    
    <filter-mapping>    
        <filter-name>struts2</filter-name>    
        <url-pattern>*.jsp</url-pattern>    
    </filter-mapping>   

<filter> 
        <filter-name>struts2</filter-name> 
        <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class> 
        <init-param> 
            <param-name>config</param-name> 
            <param-value>struts-default.xml,struts-plugin.xml,../conf/struts.xml</param-value> 
        </init-param> 
    </filter> 
    <filter-mapping> 
        <filter-name>struts2</filter-name> 
        <url-pattern>*.th</url-pattern> 
    </filter-mapping> 
    <filter-mapping> 
        <filter-name>struts2</filter-name> 
        <url-pattern>*.jsp</url-pattern> 
    </filter-mapping> 

也是就是绕过了struts的拦截器,采用servlet来上传文件~
但是这并没有解决问题,而且service不能注入了,但是可以继续开发……
希望大家能针对这个问题给出其他好的答案
问题补充:
下班了,家里没搭环境,依然期待大家的回答
问题补充:
问题搞定了~但是这个方法不知道规范不规范,功能有了,大家可以参照和改进!mxml就不贴了,参照前面。
java端参照了很多人的帖子,得知,struts2 action的原理是先把文件上传到tem路径下,然后再有fileupload拦截器拦截3个参数,最后绑定到action你设置的3个参数里。
这里我flex端没有和acion绑定,但是很我把拦截器里的方法提取到我的action中,然后也可以自己绑定到action的3个属性上(我这里没有绑定,而是直接输出到了c盘),也没有判断文件大小等等,以后再完善完善,也出个贴吧。

FileUploadAction2.java
Java代码
package com;  
 
import java.io.BufferedInputStream;  
import java.io.BufferedOutputStream;  
import java.io.File;  
import java.io.FileInputStream;  
import java.io.FileOutputStream;  
import java.io.IOException;  
import java.io.InputStream;  
import java.io.OutputStream;  
import java.util.Enumeration;  
import org.apache.struts2.ServletActionContext;  
import org.apache.struts2.dispatcher.multipart.MultiPartRequestWrapper;  
 
import com.opensymphony.xwork2.ActionSupport;  
 
public class FileUploadAction2 extends ActionSupport{  
      
    private File file;   
 
    private String fileContentType;   
 
    private String fileFileName;  
      
    public File getFile() {  
        return file;  
    }  
 
    public void setFile(File file) {  
        this.file = file;  
    }  
 
    public String getFileContentType() {  
        return fileContentType;  
    }  
 
    public void setFileContentType(String fileContentType) {  
        this.fileContentType = fileContentType;  
    }  
 
    public String getFileFileName() {  
        return fileFileName;  
    }  
 
    public void setFileFileName(String fileFileName) {  
        this.fileFileName = fileFileName;  
    }  
      
    private final int BUFFER_SIZE = 16 * 1024;  
 
    // 自己封装的一个把源文件对象复制成目标文件对象     
    private void copy(File src, File dst) {     
        InputStream in = null;     
        OutputStream out = null;  
 
        try {     
            in = new BufferedInputStream(new FileInputStream(src), BUFFER_SIZE);     
            out = new BufferedOutputStream(new FileOutputStream(dst),     
                    BUFFER_SIZE);     
            byte[] buffer = new byte[BUFFER_SIZE];     
            int len = 0;     
            while ((len = in.read(buffer)) > 0) {     
                out.write(buffer, 0, len);     
            }     
        } catch (Exception e) {     
            e.printStackTrace();     
        } finally {     
            if (null != in) {     
                try {     
                    in.close();     
                } catch (IOException e) {     
                    e.printStackTrace();     
                }     
            }     
            if (null != out) {     
                try {     
                    out.close();     
                } catch (IOException e) {     
                    e.printStackTrace();     
                }     
            }     
        }     
    }   
    private static boolean isNonEmpty(Object[] objArray) {  
        boolean result = false;  
        for (int index = 0; index < objArray.length && !result; index++) {  
            if (objArray[index] != null) {  
                result = true;  
            }  
        }  
        return result;  
    }  
 
    public void fileUpload() {  
          
        System.out.println("Access !");  
 
        MultiPartRequestWrapper multiWrapper = (MultiPartRequestWrapper)ServletActionContext.getRequest();  
          
        // Bind allowed Files  
        Enumeration fileParameterNames = multiWrapper.getFileParameterNames();  
        while (fileParameterNames != null && fileParameterNames.hasMoreElements()) {  
            // get the value of this input tag  
            String inputName = (String) fileParameterNames.nextElement();  
 
            // get the content type  
            String[] contentType = multiWrapper.getContentTypes(inputName);  
 
            if (isNonEmpty(contentType)) {  
                // get the name of the file from the input tag  
                String[] fileName = multiWrapper.getFileNames(inputName);  
 
                if (isNonEmpty(fileName)) {  
                    // Get a File object for the uploaded File  
                    File[] files = multiWrapper.getFiles(inputName);  
                    if (files != null) {  
                        for (int index = 0; index < files.length; index++) {  
                            String uploadPath = "C:\\"+fileName[index];  
                            File dstFile = new File(uploadPath);  
                            this.copy(files[index], dstFile);  
                        }  
                    }  
                }   
            }  
        }  
      
//      // 限制文件的上传大小  
//      int maxPostSize = 100 * 1024 * 1024;  
//        
//        //保存文件到服务器中  
//        DiskFileItemFactory factory = new DiskFileItemFactory();  
//        factory.setSizeThreshold(4096);  
//        ServletFileUpload upload = new ServletFileUpload(factory);  
//        upload.setSizeMax(maxPostSize);  
//        try {  
//            List fileItems = upload.parseRequest(request);  
//            Iterator iter = fileItems.iterator();  
//            while (iter.hasNext()) {  
//                FileItem item = (FileItem) iter.next();  
//                if (!item.isFormField()) {  
//                    String name = item.getName();  
//                    System.out.println(name);  
//                    try {  
//                        item.write(new File(uploadPath + name));  
//                    } catch (Exception e) {  
//                        e.printStackTrace();  
//                    }  
//                }  
//            }  
//        } catch (FileUploadException e) {  
//            e.printStackTrace();  
//            System.out.println(e.getMessage() + "结束");  
//        }  
    }  


package com;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.dispatcher.multipart.MultiPartRequestWrapper;

import com.opensymphony.xwork2.ActionSupport;

public class FileUploadAction2 extends ActionSupport{

    private File file;

    private String fileContentType;

    private String fileFileName;
   
    public File getFile() {
return file;
}

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

public String getFileContentType() {
return fileContentType;
}

public void setFileContentType(String fileContentType) {
this.fileContentType = fileContentType;
}

public String getFileFileName() {
return fileFileName;
}

public void setFileFileName(String fileFileName) {
this.fileFileName = fileFileName;
}
   
    private final int BUFFER_SIZE = 16 * 1024;

// 自己封装的一个把源文件对象复制成目标文件对象  
    private void copy(File src, File dst) {  
        InputStream in = null;  
        OutputStream out = null;

        try {  
            in = new BufferedInputStream(new FileInputStream(src), BUFFER_SIZE);  
            out = new BufferedOutputStream(new FileOutputStream(dst),  
                    BUFFER_SIZE);  
            byte[] buffer = new byte[BUFFER_SIZE];  
            int len = 0;  
            while ((len = in.read(buffer)) > 0) {  
                out.write(buffer, 0, len);  
            }  
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally {  
            if (null != in) {  
                try {  
                    in.close();  
                } catch (IOException e) {  
                    e.printStackTrace();  
                }  
            }  
            if (null != out) {  
                try {  
                    out.close();  
                } catch (IOException e) {  
                    e.printStackTrace();  
                }  
            }  
        }  
    }
    private static boolean isNonEmpty(Object[] objArray) {
        boolean result = false;
        for (int index = 0; index < objArray.length && !result; index++) {
            if (objArray[index] != null) {
                result = true;
            }
        }
        return result;
    }

public void fileUpload() {

System.out.println("Access !");

MultiPartRequestWrapper multiWrapper = (MultiPartRequestWrapper)ServletActionContext.getRequest();

        // Bind allowed Files
        Enumeration fileParameterNames = multiWrapper.getFileParameterNames();
        while (fileParameterNames != null && fileParameterNames.hasMoreElements()) {
            // get the value of this input tag
            String inputName = (String) fileParameterNames.nextElement();

            // get the content type
            String[] contentType = multiWrapper.getContentTypes(inputName);

            if (isNonEmpty(contentType)) {
                // get the name of the file from the input tag
                String[] fileName = multiWrapper.getFileNames(inputName);

                if (isNonEmpty(fileName)) {
                    // Get a File object for the uploaded File
                    File[] files = multiWrapper.getFiles(inputName);
                    if (files != null) {
                        for (int index = 0; index < files.length; index++) {
                        String uploadPath = "C:\\"+fileName[index];
                        File dstFile = new File(uploadPath);
                        this.copy(files[index], dstFile);
                        }
                    }
                }
            }
        }

// // 限制文件的上传大小
// int maxPostSize = 100 * 1024 * 1024;
//
//        //保存文件到服务器中
//        DiskFileItemFactory factory = new DiskFileItemFactory();
//        factory.setSizeThreshold(4096);
//        ServletFileUpload upload = new ServletFileUpload(factory);
//        upload.setSizeMax(maxPostSize);
//        try {
//            List fileItems = upload.parseRequest(request);
//            Iterator iter = fileItems.iterator();
//            while (iter.hasNext()) {
//                FileItem item = (FileItem) iter.next();
//                if (!item.isFormField()) {
//                    String name = item.getName();
//                    System.out.println(name);
//                    try {
//                        item.write(new File(uploadPath + name));
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }
//                }
//            }
//        } catch (FileUploadException e) {
//            e.printStackTrace();
//            System.out.println(e.getMessage() + "结束");
//        }
}
}
分享到:
评论

相关推荐

    flex+spring+struts2+ibatis 整合的eclipse工程

    flex+spring+struts2+ibatis 整合的eclipse工程,可以导入eclipse环境下直接使用,因为加入开发的jar大于了上传的最大限制,只能把jar另外打包上传,下载可以从我上传资源的lib1,lib2下载,这个工程的搭建花费了我两...

    Flex+Java多文件上传

    本话题将详细探讨“Flex+Java多文件上传”这一技术实现,结合提供的标签“源码”和“工具”,我们将深入理解如何利用Adobe Flex(一种RIA开发框架)与Java后台进行协同工作,实现高效的文件上传功能。 首先,Flex是...

    flex struts2文件上传

    Flex Struts2文件上传是一个常见的Web开发任务,它涉及到客户端与服务器端的数据交互,特别是涉及用户界面和后端服务之间的文件传输。Flex是Adobe开发的一个富互联网应用(RIA)框架,用于创建动态、交互式的用户...

    flex + servlet 多文件上传

    总的来说,这个示例展示了如何使用`Flex`作为前端,结合`Servlet`(可能在`Struts`框架下)作为后端,实现多文件上传功能,并解决了常见的中文乱码问题。这对于需要构建交互性强且支持多文件上传的Web应用来说,是一...

    Flex 与 Struts2 ByteArray 数据上传

    标题中的“Flex 与 Struts2 ByteArray 数据上传”指的是在Web开发中,使用Adobe Flex作为前端客户端,通过Struts2框架在后端处理字节数组(ByteArray)数据的上传技术。Flex是一种基于Adobe Flash Player或Adobe AIR...

    xyzp_flex_flex+java的档案管理系统_Flex+Java_XYZP_

    1. 档案上传:用户可以通过友好的界面将各种格式的文档上传到系统中,系统会自动对文件进行分类、命名和版本管理。 2. 档案检索:利用全文搜索引擎或自定义索引,用户可以快速找到所需档案,支持关键词、日期、作者...

    Flex+java上传开发工具包

    2. **异步上传**:利用Java和Flex的通信机制,文件上传可以在后台线程进行,不会阻塞用户界面,提升用户体验。 3. **安全性**:可以添加验证规则,限制文件类型和大小,防止恶意文件上传,确保系统安全。 4. **错误...

    SSH+Flex项目

    SSH+Flex项目是一种基于Flex前端和SSH2(Spring、Struts2、Hibernate)后端框架的开发模式,结合MySql数据库,实现了一套完整的Web应用系统。这种模式常用于构建功能丰富的交互式用户界面,同时提供了强大的数据管理...

    Struts2使用FlashFileUpload.swf实现批量文件上传

    以前做.net时,用过一个FlashFileUpload.swf批量文件上传工具,很帅很简单。 网址:http://www.codeproject.com/KB/aspnet/FlashUpload.aspx 因为这个用Flex写的客户端插件公开源码,而且实现的的相当完美,在asp...

    flex_java文件上传(一)

    而Java作为后端语言,提供了强大的服务器端处理能力,如Spring MVC或Struts等框架可以很好地处理文件上传请求。 1. **Flex中的文件选择组件**: Flex提供了一个FileReference类,用于处理文件选择和上传。通过创建...

    多文件上传

    在多文件上传的场景下,Flex可以用于设计用户界面,包括文件选择按钮、进度条和上传状态显示等元素。 SWFUpload则是一个JavaScript和Flash相结合的文件上传插件。它利用Flash的多文件选择特性,可以在不支持HTML5的...

    flex 上传,包含服务端

    4. **WebApplication2**:在提供的文件列表中,"WebApplication2"可能是一个基于Java的Web应用,如Spring MVC或Struts,它可能包含了服务端处理文件上传的控制器、模型和视图。控制器接收Flex客户端的HTTP请求,模型...

    flex上传下载 并解决中文乱码

    在本主题中,我们将深入探讨如何使用Flex进行文件上传和下载,并解决过程中可能出现的中文乱码问题。 一、Flex文件上传 1. Flex组件:Flex中可以使用`FileReference`组件来实现文件上传。用户通过选择文件后,`...

    FLEX上传下载的FLEX项目源码.docx

    在J2EE开发中,文件上传下载是一个常见的功能,传统的解决方案如SmartUpload和Apache的FileUpload等虽然成熟,但在Struts+Spring+Hibernate(SSH)这一流行的Java企业级应用框架下,这些工具可能显得过于复杂。...

    Flex上传压缩文件到服务器路径并解压存进数据库

    2. **文件上传**: 文件上传是通过HTTP协议的POST请求实现的。Flex客户端通过HTTPService或WebService组件向服务器发送文件数据。文件通常以二进制流的形式发送,服务器端需要正确解析这个流以接收文件。 3. **...

    BlazeDS 数据通信技术

    1. **创建Flex前端界面**:设计一个包含文件上传控件的Flex用户界面。 2. **配置BlazeDS通道**:确保Flex前端正确配置了与服务器端通信所需的通道。 3. **实现文件上传逻辑**:在Flex端编写代码来读取文件并将其发送...

    ssh嵌入flex实现在线拍照,并付图片预览

    这里可能涉及到权限控制、文件上传限制以及图片格式转换等逻辑。Struts控制器处理这些业务逻辑,将结果返回给Flex前端,可能是确认图片已保存或者显示错误信息。 在前端,用户可以实时预览所拍摄的照片,这需要Flex...

    Flex和java后台结合的视频网站源码

    - 视频上传:用户上传视频文件,后端处理存储和编码,可能涉及ffmpeg等工具。 - 视频播放:使用Flash Player或HTML5播放器,支持流媒体技术如RTMP或HLS,提供流畅的播放体验。 - 视频搜索:实现关键字搜索,可能...

    java 常用代码

    7. **Struts2**:Struts2是一个基于MVC(Model-View-Controller)设计模式的Java Web开发框架,用于构建结构清晰、易于维护的Web应用。它提供了丰富的拦截器、插件机制和模板技术,简化了开发流程。 8. **WinForm**...

    11种项目开发实例

    9. **网络硬盘(Struts 2+Hibernate+Spring实现)**:类似于云存储服务,这个系统可能包括文件上传、下载、共享和权限管理等功能,展示了Java EE技术栈在构建企业级服务方面的实力。 10. **基于ASP.NET的工作流批核...

Global site tag (gtag.js) - Google Analytics