struts 实现文件上传

<form action="fileupload.action" method="post" enctype ="multipart/form-data">

      <input type="file" name="file"><br>

      <input type="submit" value="submit">

 </form>
jsp中的表单
package com.actions;



import java.io.*;



import org.apache.struts2.ServletActionContext;



import com.opensymphony.xwork2.ActionSupport;



public class FileUploadActions extends ActionSupport {

	private static final int BUFFER_SIZE=16*1024;

	private File file;

	private String contentType;

	private String fileName;

	public File getFile() {

		return file;

	}

	public void setFile(File file) {

		this.file = file;

	}

	public void setFileContentType(String contentType) {

		this.contentType = contentType;

	}

	public void setFileFileName(String fileName) {

		this.fileName = fileName;

	}

	public String execute(){

		File dstFile=new File(ServletActionContext.getServletContext().getRealPath("/upload"+"/"+fileName));

		try {

			InputStream is=new BufferedInputStream(new FileInputStream(file),BUFFER_SIZE);

			OutputStream os=new BufferedOutputStream(new FileOutputStream(dstFile),BUFFER_SIZE);

			byte[] buffer=new byte[BUFFER_SIZE];

			while(is.read(buffer)>0){

				os.write(buffer);

			}

			is.close();

			os.close();

		} catch (Exception e) {

			// TODO Auto-generated catch block

			e.printStackTrace();

		}

		return SUCCESS;

	}

}

action代码
 
<action name="fileupload" class="com.actions.FileUploadActions">

		<interceptor-ref name="fileUpload">

			<param name="allowedTypes">

				image/bmp,image/png,image/gif,image/jpeg

			</param>

		</interceptor-ref>

		<interceptor-ref name ="defaultStack" />    

		<result name="input">index.jsp</result>

		<result name="success">index.jsp</result>

	</action>
 

struts.xml中的代码

   在上面的代码中我分别写了setFileContentType方法和setFileFileName方法,这两个方法并没有和页面上的任何代码绑定,其实表单file不但绑定了contentType(文件类型)和FileName(文件名)。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值