struts文件上传

struts文件上传Posted on

Struts 2是通过Commons FileUpload文件上传。Commons FileUpload通过将HTTP的数据保存到制定的文件夹,然后Struts使用fileUpload拦截器将文件绑定到Action的实例中。从而我们就能够以本地文件方式的操作浏览器上传的文件。

使用到的包: commons-fileupload-1.2.1.jar和commons-io-1.3.2.jar,这两个包已经包涵在Struts2 Core Libraries中无需导入。

//接受变量命名规则

1 myFileAction{File image;String imageFileName;String imageContentType;// 获取上传文件类型 要求:文件类型名称的写法是文件属性名+ContentTypeFile getImage() { return image; }setImage(File image) { this.image = image; }String getImageFileName() { return imageFileName; }setImageFileName(String imageFileName) { this.imageFileName = imageFileName; }String getImageContentType() { return imageContentType; }setImageContentType(String imageContentType) { this.imageContentType = imageContentType; }20 21 }

以下是具体代码:jsp

(){(){);){);; 9 }].submit();11 });12 }); form的enctype属性为编码方式,网站空间,常用有两种:application/x-www-form-urlencoded(默认)和multipart/form-data 17 当action为get时候,美国空间,浏览器用x-www-form-urlencoded的编码方式把form数据18 转换成一个字串(name1=value1&name2=value2…),然后把这个字串append到url后面,加载这个新的url。19 当action为post时候,浏览器把form数据封装到http body中,美国服务器,然后发送到server。20 如果没有type=file的控件,用默认的application/x-www-form-urlencoded就可以了。但是如果有type=file的话,就要用到multipart/form-data了。21 浏览器会把整个表单以控件为单位分割,并为每个部分加上Content-Disposition(form-data或者file),22 Content-Type(默认为text/plain),name(控件name)等信息,并加上分割符(boundary)。

strus.xml

/index.jsp

Action

MyFileUploadlAction extends ActionSupport {String imageFileName;String imageContentType;* serialVersionUID = 1L; String fileUpload() {12if(image==null){13return “jsp”;14 }15File savefile = new File(“D:\\上传文件”+”/”+imageFileName); 16if(!savefile.getParentFile().exists()) 17 savefile.getParentFile().mkdirs(); 18try {19InputStream is=new BufferedInputStream(new FileInputStream(image));20OutputStream os=new BufferedOutputStream(new FileOutputStream(savefile));[4*1204];22while(is.read(buffer)>0){23 os.write(buffer);24 }25 is.close();26 os.close();27} catch (IOException e) {28 e.printStackTrace();29 } 30String[] t = imageContentType.split(“/”); 31for(String s : t) {32 System.out.println(s); 33 } 34return “jsp”;35 36 }37 38 }

展现效果:

我遇见的问题如下:Error:the request was rejected because its size (2361068) exceeds the configured maximum (2097152)

原因:你要上传的文件超过了struts默认的上传文件2M,所以要加大上传限制;外部修改struts2-core.jar->dispatcher->default.properties文件

原大小:struts.multipart.maxSize=2097152 将2097152修改成你自己设定的大小,这样在上传大文件就不会出异常。

第二你可以重写addActionError方法 去捕获异常。

Web上传的稳定性不行,所以一般不实用他上传较大文件,上传较大文件要自己写上传插件。

大理的洱海形如人耳,风平浪静时,

struts文件上传

相关文章:

你感兴趣的文章:

标签云: