Эта статья делится с вами методом реализации загрузки файлов Struts2 Framework для вашей ссылки. Конкретный контент заключается в следующем
Процесс конфигурации Struts2
(1) Добавить пакет JAR в проект
(2) Конфигурация фильтра (фильтр) в web.xml
<? xml version = "1.0" Encoding = "utf-8"?> <web-app arser = "2,5" xmlns = "http://java.sun.com/xml/ns/javaee" xmlns: xsi = "http://www.w3.org/2001/xmlschema electan "/www.w3. xsi: schemalocation = "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.x.xun.> </xmalml/ns/javaee/web-app_2_5. <filter-name> struts2 </filter-name> <filter-class> org.apache.struts2.dispatcher.ng.filter.strutspreareandexecutefilter </filter-class> </filter> <filter-mapping> <filter-mame> struts2 </filter-name> <url-pattern>/*</*</*</*</*</</*</*</*</*</*</*</*</*</*</*</*</*</*</*</*</*</*</*</*</*</*</</</filter> struts2 </filter> <url-pattern> </filter-mapping> </web-app>
(3) Написание файла конфигурации struts.xml
<? xml version = "1.0" Encoding = "UTF-8"?> <web-app версия = "2,5" xmlns = "http://java.sun.com/xml/ns/javaee" xmlns: xsi = "http://www.w3.org/2001/xmlschema-instance" xsi: schemalocati on = "http://java.sun.com/xml/ns/javaeehttp://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <sillance-Name> </display-Ame> <filter > <Filter-name> strUTS2 </filter-name> <filter-class> org.apache.struts2.dispatcher.ng.filter.strutspreareandexecutefilter </filt ER-CLASS> </filter> <Filter-Mapping> <Filter-name> Struts2 </filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
(4) Написание класса действий
пакет com.xmgc.sc.action; Импорт java.io.file; импорт java.io.fileinputstream; импорт java.io.fileoutputstream; импорт java.io.ioexception; Импорт org.apache.struts2.servletactionContext; открытый класс MyUploadAction {Private String Title; private file upload; // Имя типа файла файла в форме формы - это то же самое частное строка oploadcontentType; // Префикс должен быть вышеупомянутый загрузка частной строки uploadfilename; public String getTitle () {return title; } public void settitle (строка заголовка) {this.title = title; } public file getUpload () {return upload; } public void setUpload (upload file) {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 getavePath () {// ServletContext cxt = ServletActionContext.getServletContext (); // string path = cxt.getRealpath ("/"); // это получает путь: http: // localhost: 8080/sc // после загрузки, он становится E: /software/apache-tomcat-6.0.45/webapps/sc return savePath; } public void setSavePath (String SavePath) {//e:/software/apache-tomcat-6.0.45/webapps/sc/myupload this.savepath = ServletactionContext.getServletContext (). getRealPath ("/myUpload"); }*/public String execute () throws ioexception {System.out.println (title); // Title System.out.println (uploadcontenttype); // Тип файла файла для загрузки System.out.println (uploadfilename); // Имя файла для загрузки, запомнить, что также есть endtension system.out. String realPath = ServletActionContext.getServletContext (). GetRealPath ("/"); String Path = RealPath+"myUpload/"+uploadfilename; System.out.println (RealPath); System.out.println (path); FileInputStream fis = new FileInputStream (upload); FileOutputStream fos = new FileOutputStream (path); byte [] bytes = new Byte [1024]; // определить байтовый массив 1024 размер int len = -1; // Использование для использования в качестве битов флага, в то время как ((len = fis.read (bytes))> 0) {fos.write (bytes, 0, len); } return null; }}(5) Написание страниц JSP
<%@ page contentType="text/html;charset=utf-8"%> <!-- enctype="multipart/form-data", this is the most important configuration--><form action="myupload.action" enctype="multipart/form-data" method="post"> File name: <input type="text" name="title"/><br/> Upload: <input type="file" name = "upload"/> <br/> <input type = "Отправить" value = "upload"/> </form>
После этого резюме я чувствую, что загрузка одного файла в структуру Struts2 все еще очень проста. Просто получите адрес, который будет храниться, а затем напишите его по этому адресу через поток ввода и вывода. Для большей части работы Struts2 сделал это для нас.
Выше всего содержание этой статьи. Я надеюсь, что это будет полезно для каждого обучения, и я надеюсь, что все будут поддерживать Wulin.com больше.