В нашей веб -разработке много раз нам нужно загрузить некоторые файлы с машины на веб -сервер.
Например: система BBS, когда пользователи используют эту систему, они могут загружать некоторые изображения и документы машины на сервер. Тогда другие пользователи могут загрузить эти файлы, поэтому мы можем программировать загрузку файла сами
Но лучшим способом является использование некоторых существующих компонентов, чтобы помочь нам реализовать эту функцию загрузки.
Общие компоненты загрузки:
Commons FileUpload от Apache
Javazoom - это загрузка
jspsmartupload
upload.jsp
код;
<%@ page language = "java" contentType = "text/html; charset = utf-8"%> <html> <head> <title> с использованием загрузки Commons для загрузки файла </title> </head> <style>* {font-family: "安体"; font-size: 14px }</style><body><p align="center"> Please select the file you want to upload</p><form id="form1" name="form1" method="post" action="servlet/fileServlet" enctype="multipart/form-data"> <table align="center"> <tr> <td>Uploader: </td> <td> <input name = "name" type = "text" id = "name" size = "20"> </td> </tr> <tr> <td> Файл загрузки: </td> <td> <input name = "file" type = "size =" 20 "> </td> </tr> <tr> <td> </td> <td> <inputul type = "reset" name = "reset" value = "reset"> </td> </tr> </table> </form> </body> </html>Fileuploadservlet.java код:
/***/пакет com.b510.example; import java.io.file; import java.io.ioexception; импорт java.util.*; import javax.servlet.servletConfig; импорт javax.servlet.servletcontext; import javax.servletexception. javax.servlet.http.httpservlectrequest; import javax.servlet.http.httpservletresponse; импорт org.apache.commons.fileupload.fileitem; импорт org.apache.commons.fileupload.fileuadexception; org.apache.commons.fileupload.disk.DiskFileItemFactory;import org.apache.commons.fileupload.servlet.ServletFileUpload;/** * * @author XHW * * @date 2011-7-26 * */public class FileUploadServlet extends HttpServlet { private static final long serialVersionUID = -7744625344830285257L; Private ServletContext SC; Private String SavePath; public void Doget (httpservletrequest, httpservletresponse response) бросает Servletexception, ioException {DoPost (запрос, ответ); } public void init (конфигурация SERVLETCONFIG) {// Параметр инициализации SAVEDPATH Установлен в web.xml = config.getinitParameter ("SavePath"); sc = config.getServletContext (); } public void Dopost (httpservletrequest, httpservletresponse response) throws servletexception, ioexception {request.setcharacterencoding ("utf-8"); DiskFileItemfactory Factory = new DiskFileItemFactory (); ServletFileUpload upload = new ServletFileUpload (Factory); try {list elects = upload.parserequest (request); Итератор itr = item.iterator (); while (itr.hasnext ()) {fileitem item = (fileitem) itr.next (); if (item.isformfield ()) {System.out.println ("Имя параметра формы:" + item.getfieldname () + ", значение параметра формы:" + item.getString ("utf-8")); } else {if (item.getName ()! = null &&! item.getName (). equals ("")) {System.out.println ("Размер файла загрузки:" + item.getSize ()); System.out.println ("upload file type:" + item.getContentType ()); // item.getName () возвращает полное имя пути загруженного файла в клиентской системе. File tempfile = new File (item.getName ()); // загрузка файла файла сохранения файл файла = new File (sc.getRealPath ("/") + savePath, tempfile.getName ()); item.write (file); request.setattribute ("upload.message", "Загрузить файл успешно!"); } else {request.setAttribute ("upload.message", "Нет файла загрузки выбран!"); }}}}} catch (fileuploadexception e) {e.printstacktrace (); } catch (Exception e) {e.printstackTrace (); request.setattribute ("upload.message", "opload file не удастся!"); } request.getRequestDispatcher ("/uploadresult.jsp"). }}uploadresult.jsp код:
<%@ page language = "java" import = "java.util.*" pageencoding = "utf-8"%> <! Doctype html public "-// w3c // dtd html 4.01 Transitional // en"> <html> <Head> uploadResult </title> <meta http-queciv = "haute> uploadResult </title> <Meta http-ockiv =" content = "no-cache"> <meta http-equiv = "cache-control" content = "no-cache"> <meta http-equiv = "expires" content = "0"> <meta http-equiv = "Keywords" Content = "Ключевое слово1, ключевое слово2, ключевое слово3"> <meta http-equivive = "description1 hite his his hite his his hit eavize =" rel = "styleSheet" type = "text/css" href = "styles.css" rel = "внешний nofollow"> -> </head> <body> $ {requestScope ['upload.message']} <a href = "/upload/uploadfile.jsp" rel = nofutold "> upload file </a> </hody> </hp> </hptml> </hp> </hp> </hp> </hp> </hptml> </hp> </hp> </hp> </hptml> </hp> </hptml> </hptml.web.xml
<SERVLET> <SOMNAD> Это описание моего компонента J2EE </description> <SIVEL-name> Это отображаемое имя моего J2EE Component </display-name> <servlet-name> fileuploadServlet </servlet-name> <vervlet-class> com.b510.example.fileuploadservlet </servlet-class> <! --Set initialization parameters --> <init-param> <param-name>savePath</param-name> <param-value>uploads</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>FileUploadServlet</servlet-name> <url-pattern>/servlet/fileServlet</url-pattern> </servlet-mapping>
Эта статья была составлена в «Краткое описание методов операции загрузки Java», и все могут учиться и прочитать.
Выше всего содержание этой статьи. Я надеюсь, что это будет полезно для каждого обучения, и я надеюсь, что все будут поддерживать Wulin.com больше.