编写jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title></title> </head> <body> <!--enctype="multipart/form-data"文件以二进制上传 --> <form action="files.action" method="post" enctype="multipart/form-data"> <input name="files" type="file"><!--这里的name="files"必须和action中的属性名对应 (private File files;) --> <input type="submit" > </form> </body> </html>
编写action处里请求
package action; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; public class filesAction { private File files; public File getFiles() { return files; } public void setFiles(File files) { this.files = files; } public String execute() throws Exception{ //输出流,并指定输出路径 FileOutputStream fos=new FileOutputStream("f:/abc.rar"); //创建输入流读取文件 FileInputStream fis=new FileInputStream(files); //创建字节数组设置缓冲区 byte[] bytes=new byte[1024]; int len=fis.read(bytes); //边写入边读取二进制 while(len>0){ //趁着读取字节未覆盖原来的字节前,把其写入硬盘 fos.write(bytes); //继续读取字节直到读取完 len=fis.read(); } fos.flush(); fos.close(); fis.close(); return "success"; } }
Struts.xml配置文件
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd"> <struts> <package name="default" namespace="/" extends="struts-default"> <action name="files" class="action.filesAction"> <result name="success">index.jsp</result> </action> </package> </struts>
运行结果
时间: 2024-11-05 00:30:58