选择所要上传的文件
upload.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags" %> <%//引入struts2标签 %>Insert title here
<% // |
file | |
| |
实现文件上传功能
UploadAction.java
import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.InputStream;import java.io.OutputStream;import org.apache.struts2.ServletActionContext;import com.opensymphony.xwork2.ActionSupport;public class UploadAction extends ActionSupport{private File file; //创建file属性private String fileFileName; //创建fileFileName属性,代表文件名称private String fileContentType; //创建fileContentType属性,代表文件类型 public File getFile() { return file; }public void setFile(File file) { this.file = file; }public String getFileFileName() { return fileFileName; }public void setFileFileName(String fileFileName) { this.fileFileName = fileFileName; }public String getFileContentType() { return fileContentType; }public void setFileContentType(String fileContentType) { this.fileContentType = fileContentType; }public String execute() throws Exception{ InputStream is = new FileInputStream(file); String root = "E:/shang"; //设置上传的路径 File destFile = new File(root, this.getFileFileName()); //destFile文件:输出流的目的文件 OutputStream os = new FileOutputStream(destFile); //os文件:关于destFile文件的输出流 byte[] buffer = new byte[400]; //buffer字节数组:实现输入流与输出流的转换 int length = 0; while ((length = is.read(buffer)) > 0) { os.write(buffer, 0, length); } is.close(); os.close(); return SUCCESS; }}
配置struts.xml 文件
uploadResult.jsp