Java Web——映像上傳

來源:互聯網
上載者:User

標籤:extend   file   ted   ring   att   大小限制   建立   dir   儲存   

一、jsp中:

 1 <body> 2     <!-- 注意: 1. type="file"; 2.method="post" ; 3.enctype="multipart/form-data" --> 3     <form action="UploadServlet" method="post" enctype="multipart/form-data"> 4         僱員編號:<input type="text" name="empno"/><br/><br/> 5         僱員姓名:<input type="text" name="ename"/><br/><br/> 6         所在部門: 7                 <select name="deptno"> 8                     <option value="10">銷售部</option> 9                     <option value="20">IT部</option>10                     <option value="30">人力部</option>11                 </select><br/><br/>12         驗證碼:<input type="text" name="code"><img id="code" alt="請重新整理" src="validateCodeServlet" onclick="changeCode()" style="cursor:hand;"><a href="javascript:changeCode()">換一張</a><br/><br/>13         14             15         頭像:<input type="file" name="uploadFile">16             <img src="${image_path}" title="${image_name}" width="200" height="200">17         <br/><br/>18         19         <input type="reset" value="重設"/> 20         <input type="submit" value="註冊"/> 21     </form>22 </body>23 </html>

 

 

 

二、匯入工具包

 

三、servlet中取得資料

 

package servlet;import java.io.File;import java.io.IOException;import java.util.Date;import java.util.Iterator;import java.util.List;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;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;/** * Servlet implementation class UploadServlet */@WebServlet("/UploadServlet")public class UploadServlet extends HttpServlet {    private static final long serialVersionUID = 1L;    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {        doPost(request, response);    }        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {        //判斷上傳表單是否為multipart/form-data類型        if(ServletFileUpload.isMultipartContent(request))        {                        try {                //1. 建立DiskFileItemFactory對象,設定緩衝區大小和臨時檔案目錄                DiskFileItemFactory factory = new DiskFileItemFactory();                //System.out.println(System.getProperty("java.io.tmpdir"));//預設臨時檔案夾                                //2. 建立ServletFileUpload對象,並設定上傳檔案的大小限制。                ServletFileUpload  sfu = new ServletFileUpload(factory);                sfu.setSizeMax(10*1024*1024);//以byte為單位    不能超過10M  1024byte = 1kb  1024kb=1M 1024M = 1G                sfu.setHeaderEncoding("utf-8");                                //3. 調用ServletFileUpload.parseRequest方法解析request對象,得到一個儲存了所有上傳內容的List對象。                List<FileItem> fileItemList = sfu.parseRequest(request);                Iterator<FileItem> fileItems = fileItemList.iterator();                                //4. 遍曆list,每迭代一個FileItem對象,調用其isFormField方法判斷是否是上傳檔案                while(fileItems.hasNext())                {                    FileItem fileItem = fileItems.next();                    //普通表單元素                    if(fileItem.isFormField())                    {                        String name = fileItem.getFieldName();//name屬性值                        String value = fileItem.getString("utf-8");//name對應的value值                                                System.out.println(name + " = "+value);                    }                    //<input type="file">的上傳檔案的元素                    else                    {                        String fileName = fileItem.getName();//檔案名稱                        System.out.println("原檔案名稱:" + fileName);//Koala.jpg                                                String suffix = fileName.substring(fileName.lastIndexOf(‘.‘));                        System.out.println("副檔名:" + suffix);//.jpg                                                //新檔案名稱(唯一)                        String newFileName = new Date().getTime() + suffix;                        System.out.println("新檔案名稱:" + newFileName);//image\1478509873038.jpg                                                //5. 調用FileItem的write()方法,寫入檔案                        File file = new File(request.getServletContext().getRealPath("image")+"\\"+newFileName);                        System.out.println(file.getAbsolutePath());                        fileItem.write(file);                                                //6. 調用FileItem的delete()方法,刪除臨時檔案                        fileItem.delete();                                                /*                         * 儲存到資料庫時注意                         *     1.儲存源檔案名稱   Koala.jpg                         *  2.儲存相對路徑      image/1478509873038.jpg                         *                          */                        request.setAttribute("image_name",fileName);                        request.setAttribute("image_path","image/"+newFileName);                        request.getRequestDispatcher("/upload.jsp").forward(request, response);                    }                }                            } catch (FileUploadException e) {                e.printStackTrace();            } catch (Exception e) {                e.printStackTrace();            }                                }    }}

 

Java Web——映像上傳

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.