package com.bjsxt.test; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import com.opensymphony.xwork2.ActionSupport; public class Upload2Action extends ActionSupport { private String title; private File upload; //封装上传文件域 private String uploadContentType; //封装上传文件类型 private String uploadFileName; //封装上传文件名 private String savePath; public String execute() throws Exception{ System.out.println(uploadFileName); System.out.println(uploadContentType); FileOutputStream fos = new FileOutputStream(getSavePath()+getUploadFileName()); FileInputStream fis = new FileInputStream(upload); byte[] buf = new byte[1024]; int len = 0; while((len = fis.read(buf))>0){ fos.write(buf, 0, len); } fos.close(); fis.close(); return SUCCESS; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public File getUpload() { return upload; } public void setUpload(File upload) { this.upload = upload; } public String getUploadContentType() { return uploadContentType; } public void setUploadContentType(String uploadContentType) { this.uploadContentType = uploadContentType; } public String getUploadFileName() { return uploadFileName; } public void setUploadFileName(String uploadFileName) { this.uploadFileName = uploadFileName; } public String getSavePath() { return savePath; } public void setSavePath(String savePath) { this.savePath = savePath; } }
<action name="Upload" class="com.bjsxt.test.Upload2Action"> <param name="savePath">d:/temp/</param> <!-- 可以通过这种方式在配置文件中设置action属性的值 --> <result name="input">/uploadFile.jsp</result> <result name="success">/upload_ok.jsp</result> </action>
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <form action="Upload" enctype="multipart/form-data" method=post > 文件标题:<input type=text name=title /> <br/> 选择文件:<input type=file name=upload /><br/> <input type=submit value=上传 /> </form>