檔案上傳代碼

來源:互聯網
上載者:User

標籤:

1.0先在頁面上初始化

代碼

<title>檔案上傳</title>      </head>    <body>    <form enctype="multipart/form-data" action="test.jsp" method="post">        名稱:<input type="text" name="username" /><br>        檔案:<input type="file" name="myfile" /><br/>        <input type="submit" value="提交"/>    </form>  </body></html>

enctype=多部分的表單資料,並且如果form表單的屬性中多了enctype="multipart/form-data",是不能使用request.getParameter(name屬性的)

1.12:在WEB-ROOT的根目錄下建立一個test.jsp,實現檔案上傳功能!

 

<%@page import="java.io.File"%><%@page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%><%@page import="org.apache.commons.fileupload.FileItem" %><%@page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%><%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%    //解決亂碼    request.setCharacterEncoding("utf-8");    //將使用者傳遞過來的request的內容顯示出來,判斷類型,如果是常規的普通表單,那麼執行方式一    //否則是檔案域,執行方式二    //01.判斷是普通表單還是檔案上傳    boolean flag=ServletFileUpload.isMultipartContent(request);    if(flag)    {        //定義一個解析器,來解析請求中的各個項目        DiskFileItemFactory factory=new DiskFileItemFactory();        //解析upload建立成功        ServletFileUpload upload=new ServletFileUpload(factory);        List<FileItem> filelist=upload.parseRequest(request);        //每一個FileItem都代表了一個表單元素        Iterator<FileItem> mytor=filelist.iterator();        while(mytor.hasNext())        {            FileItem item=mytor.next();            if(item!=null)            {                //對當前進行驗證,是普通表單還是檔案上傳                if(item.isFormField())    //證明是普通表單欄位                {                    //擷取該表單元素內容(value值)                    String name=item.getFieldName();                    //表單的name屬性而不是value值                    if(name.equals("username"))                    {                        out.print(item.getString("utf-8"));                    }                                    }else{//是檔案上傳                    String filename=item.getName();                    //扔到伺服器目錄下                        String path="/WEB-INF/folder";//相對路徑                    String paths=this.getServletContext().getRealPath(path);                    out.print(paths);                    File file=new File(filename);                    File uploadFile=new File(paths,file.getName());                    item.write(uploadFile);                    out.print("上傳成功");                }            }        }    }%>

檔案上傳代碼

聯繫我們

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