1. Постройте среду Struts2
Под MyeClipse, щелкните правой кнопкой мыши проект -> MyeClipse -> Project Facets -> Установить Apache Struts2.
Если вы хотите создать его самостоятельно, вам нужно загрузить пакет Struts2 и написать файл конфигурации Struts.xml.
Конфигурация файла web.xml заключается в следующем:
<Filter> <Filter-name> StrUTS2 </filter-name> <filter-class> org.apache.struts2.dispatcher.ng.filter.strutspreareandexecutefilter </filter-class> <urlter> <filter-mapping> <filter-name> struts2 </filter-mane> <url-p-p-p-p-p-p-p-p-p-p-p-p-p-p-p-p-p-p-p-p-p-p-p-p-prapping>. </filter-карты>
2. Загрузка файла
1. Страница стойки регистрации:
Загрузить страницу:
<body> <form action = "upload.action" method = "post" enctype = "multipart/form-data"> <input type = "file" name = "upload"/> <input type = "Vade =" pospent "/> <br> $ {result} </form> </body>Атрибут входного имени соответствует именованию фона.
Страница загрузки не удалась:
<body> <h2> выгрузка не удалась </h2> <s: Fielderror> </s: Fielderror> </body>
нуждаться:
<%@ taglib uri = "/struts-tags" prefix = "s"%>
2. Бэкэнд -действие
Основные свойства Загрузка, загрузка ContentType, uploadfilename.
пакет com.yf.action; import java.io.file; import org.apache.commons.io.fileutils; import org.apache.struts2.servletactoncontext; импорт com.opensymphony.xwork2.actionsupport; public class uploadaction расширяет actionsupport {private file upload; Private String uploadContentType; Private String uploadfilename; частная строковая результат; public file getUoload () {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 getResult () {return Result; } public void setResult (String Result) {this.Result = result; } @Override public String execute () throws exception {String path = ServletActionContext.getServletContext (). GetRealPath ("/images"); File file = new File (path); if (! file.exists ()) {file.mkdir (); } System.out.println (upload); Fileutils.copyfile (upload, new File (file, uploadfilename)); result = "Загружено успешно"; вернуть успех; }}3.STRUTS.xml Configurational
Настройте действие и настройте Interceptor, чтобы ограничить тип и размер загруженных файлов.
<?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> <constant name="struts.enable.DynamicMethodInvocation" value="false"/> <constant name="struts.devMode" value="true"/> <constant name="struts.multipart.saveDir" value="/tmp"/> <constant name="struts.custom.i18n.resources" value="app"></constant> <package name="default" namespace="/" extends="struts-default"> <name Action = "upload"> <suld>/index.jsp </result> <name = "input">/error.jsp </result> <!-Настройка перехватчика для ограничения типа и размера загруженных файлов-> <receptor-ref name = "fileupload"> <parame = "Alludtypes"> image/bmp, image/x-png, image/kam name = "maximumSize"> 2m </param> </receptor-ref> <receptor-ref name = "defaultstack"> </receptor-ref> </action> </package> </struts>
4. Создайте новый файл свойств
Неудачная информация загрузки файла отображается на переднем плане, а сообщение об ошибке отображается при обработке.
Содержимое файла следующее:
struts.messages.error.file.too/large =/u4e0a/u4f20/u6587/u4ef6/u592a/u5927/u4e86/uff01struts.m essages.error.content.type.not.allowed =/u4e0a/u4f20/u6587/u4ef6/u7c7b/u578b/u4e0d/u7b26/uff01
То есть добавить:
Имя: struts.messages.error.file.too/large
Значение: файл загрузки слишком велик!
Имя: struts.messages.error.content.type.not.allowed
Значение: загруженный тип файла не совпадает!
Результаты работы следующие:
Выберите JPG Image, размер не превышает 2 м, после запуска
Выберите файл без картины:
Если вам нужно загружать файлы партиями, измените фона загрузку, загрузку contenttype и uploadfilename для списка, прочитайте файл загрузки в цикле и сохраните его на жесткий диск, добавьте ввод на стойку регистрации, а атрибут имени одинаково.
Выше приведено примером анализа функции загрузки файла strUTS2, введенной редактором. Я надеюсь, что это будет полезно для всех. Если у вас есть какие -либо вопросы, пожалуйста, оставьте мне сообщение. Редактор ответит всем вовремя!