欢迎 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() + "结束");
// }
}
}
我的参与
我的闲聊
我的圈子
我的收藏
我的博客 设置 退出
问答首页 → 问答分类: 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() + "结束");
// }
}
}