java三種方式實現檔案的上傳
1:
實現檔案的上傳可以有好多途徑,最簡單的就是用sun公司提供的File類,可以簡單的實現檔案的上傳和顯示:
try { InputStream stream = file.getInputStream();//把檔案讀入 Savefilepath = request.getRealPath("/upload");//將檔案存放在當前系統路徑的哪個資料夾下 Savefilename = getNewFilename(file.getFileName()); Savefilepath = Savefilepath + "\\" + Savefilename; OutputStream bos = new FileOutputStream(Savefilepath);//建立一個上傳檔案的輸出流 int bytesRead = 0; byte[] buffer = new byte[10*1024]; while ( (bytesRead = stream.read(buffer, 0, 10240)) != -1) { bos.write(buffer, 0, bytesRead);//將檔案寫入伺服器的硬碟上 } bos.close(); stream.close(); }catch(Exception e){ e.printStackTrace(); } |
2:
簡單的程式碼如下,於此同時有一個很簡單的擴充套件的jspsmart很好用,他是封裝好的一些上傳的組建,做一些上傳的優化,下面就是簡單實現上傳的例子:
上傳頁面: <html> <head> <title>smartupload</title> </head> <body> <form action="smartupload02.jsp" method="post" enctype="multipart/form-data"> 上傳的圖片:<input type="file" name="pic"> <input type="submit" value="上傳"> </form> </body> </html> 處理頁面: <%@ page language="java" import="java.util.*" pageEncoding="GBK"%> <jsp:useBean id="smartupload" class="org.lxh.smart.SmartUpload"/> <html> <head> <title>smartupload</title> </head> <body> <% smartupload.initialize(pageContext) ; // 初始化上傳 smartupload.upload() ; // 準備上傳 smartupload.save("upload") ; // 儲存檔案 %> </body> </html> |
3:
最後就是servlet3.0的新特性裡面的上傳檔案的新特性,他則是採用part來實現的,下面是簡單的例子:
package com.simple; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.Part; import com.sun.xml.ws.wsdl.parser.Part; public class uploadServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); Part part = request.getPath("file"); String name = part.getName(); String url = request.getSession().getServletContext().getRealPath("/upload"); String reqName = request.getHeader("content-disposition"); String fileName = reqName.substring(reqName.lastIndexOf("=")+2, reqName.length()-1); part.write(url+"/"+fileName); } } |
其實功能是一樣的,要求也就是以實現功能為宗旨,但是多學習點東西總是好的。