編寫jsphtml
<%@ 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處裏請求java
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配置文件apache
<?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>
運行結果數組