java組件fileupload檔案上傳demo_java

來源:互聯網
上載者:User

在我們的web開發中,很多的時候都需要把原生一些檔案上傳到web伺服器上面去。

如:一個BBS系統,當使用者使用這是系統的時候,能把原生一些圖片,文檔上傳到伺服器上面去。然後其他使用者可以去下載這些檔案,那麼這樣的話,我們可以自己編程實現檔案的上傳,但是更好的方式是使用一些已有的組件協助我們實現這種上傳功能。

常用的上傳組件:  

    Apache 的 Commons FileUpload

    JavaZoom的UploadBean

    jspSmartUpload

FileUpload下載地址:

  http://commons.apache.org/fileupload/

  下載:commons-fileupload-1.2.2-bin.zip    得到:commons-fileupload-1.2.2.jar

  http://commons.apache.org/io/

  下載:commons-io-1.4-bin.zip       得到:commons-io-1.4.jar

upload.jsp

代碼;

<%@ page language="java" contentType="text/html; charset=UTF-8"%><html><head><title>using commons Upload to upload file </title></head><style>* { font-family: "宋體"; font-size: 14px }</style><body><p align="center"> 請您選擇需要上傳的檔案</p><form id="form1" name="form1" method="post" action="servlet/fileServlet" enctype="multipart/form-data"> <table border="0" align="center"> <tr> <td>上傳人:</td> <td> <input name="name" type="text" id="name" size="20" ></td> </tr>  <tr> <td>上傳檔案:</td> <td><input name="file" type="file" size="20" ></td> </tr>  <tr>  <td></td><td> <input type="submit" name="submit" value="提交" > <input type="reset" name="reset" value="重設" > </td> </tr> </table></form></body></html>

FileUploadServlet.java代碼:

package com.b510.example;import java.io.File;import java.io.IOException;import java.util.*;import javax.servlet.ServletConfig;import javax.servlet.ServletContext;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.commons.fileupload.FileItem;import org.apache.commons.fileupload.FileUploadException;import 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 request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); }  public void init(ServletConfig config) { // 在web.xml中設定的一個初始化參數 savePath = config.getInitParameter("savePath"); sc = config.getServletContext(); }  public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); try { List items = upload.parseRequest(request); Iterator itr = items.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("上傳檔案的類型:" + item.getContentType());  // item.getName()返回上傳檔案在用戶端的完整路徑名稱  System.out.println("上傳檔案的名稱:" + item.getName());  File tempFile = new File(item.getName());  //上傳檔案的儲存路徑  File file = 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", "上傳檔案失敗!"); } request.getRequestDispatcher("/uploadResult.jsp").forward(request, response); }}

uploadResult.jsp代碼:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head>  <title>uploadResult</title>  <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0">  <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head>  <body> ${requestScope['upload.message'] } <a href="/upload/uploadFile.jsp">上傳檔案</a> </body></html>

web.xml

代碼:

<?xml version="1.0" encoding="UTF-8"?><web-app version="2.5"  xmlns="http://java.sun.com/xml/ns/javaee"  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee  http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <servlet> <description>This is the description of my J2EE component</description> <display-name>This is the display name of my J2EE component</display-name> <servlet-name>FileUploadServlet</servlet-name> <servlet-class>com.b510.example.FileUploadServlet</servlet-class>  <!--設定初始化參數--> <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> <welcome-file-list> <welcome-file>index.jsp</welcome-file> <welcome-file>uploadFile.jsp</welcome-file> </welcome-file-list></web-app>

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援雲棲社區。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.