Servlet實現檔案上傳的幾種方法
1. 通過getInputStream()取得上傳檔案。
/** * To change this template, choose Tools | Templates * and open the template in the editor. */ package net.individuals.web.servlet; import java.io.DataInputStream; import java.io.FileOutputStream; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * * @author Barudisshu */ @WebServlet(name = "UploadServlet", urlPatterns = {"/UploadServlet"}) public class UploadServlet extends HttpServlet { /** * Processes requests for both HTTP * <code>GET</code> and * <code>POST</code> methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); //讀取請求Body byte[] body = readBody(request); //取得所有Body內容的字串表示 String textBody = new String(body, "ISO-8859-1"); //取得上傳的檔名稱 String fileName = getFileName(textBody); //取得檔案開始與結束位置 Position p = getFilePosition(request, textBody); //輸出至檔案 writeTo(fileName, body, p); } //構造類 class Position { int begin; int end; public Position(int begin, int end) { this.begin = begin; this.end = end; } } private byte[] readBody(HttpServletRequest request) throws IOException { //獲取請求文字位元組長度 int formDataLength = request.getContentLength(); //取得ServletInputStream輸入流物件 DataInputStream dataStream = new DataInputStream(request.getInputStream()); byte body[] = new byte[formDataLength]; int totalBytes = 0; while (totalBytes < formDataLength) { int bytes = dataStream.read(body, totalBytes, formDataLength); totalBytes += bytes; } return body; } private Position getFilePosition(HttpServletRequest request, String textBody) throws IOException { //取得檔案區段邊界資訊 String contentType = request.getContentType(); String boundaryText = contentType.substring(contentType.lastIndexOf("=") + 1, contentType.length()); //取得實際上傳檔案的氣勢與結束位置 int pos = textBody.indexOf("filename=\""); pos = textBody.indexOf("\n", pos) + 1; pos = textBody.indexOf("\n", pos) + 1; pos = textBody.indexOf("\n", pos) + 1; int boundaryLoc = textBody.indexOf(boundaryText, pos) - 4; int begin = ((textBody.substring(0, pos)).getBytes("ISO-8859-1")).length; int end = ((textBody.substring(0, boundaryLoc)).getBytes("ISO-8859-1")).length; return new Position(begin, end); } private String getFileName(String requestBody) { String fileName = requestBody.substring(requestBody.indexOf("filename=\"") + 10); fileName = fileName.substring(0, fileName.indexOf("\n")); fileName = fileName.substring(fileName.indexOf("\n") + 1, fileName.indexOf("\"")); return fileName; } private void writeTo(String fileName, byte[] body, Position p) throws IOException { FileOutputStream fileOutputStream = new FileOutputStream("e:/workspace/" + fileName); fileOutputStream.write(body, p.begin, (p.end - p.begin)); fileOutputStream.flush(); fileOutputStream.close(); } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP * <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP * <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
2. 通過getPart()、getParts()取得上傳檔案。
body格式:
POST http://www.example.com HTTP/1.1 Content-Type:multipart/form-data; boundary=----WebKitFormBoundaryrGKCBY7qhFd3TrwA ------WebKitFormBoundaryrGKCBY7qhFd3TrwA Content-Disposition: form-data; name="text" title ------WebKitFormBoundaryrGKCBY7qhFd3TrwA Content-Disposition: form-data; name="file"; filename="chrome.png" Content-Type: image/png PNG ... content of chrome.png ... ------WebKitFormBoundaryrGKCBY7qhFd3TrwA--
/** * To change this template, choose Tools | Templates * and open the template in the editor. */ package net.individuals.web.servlet; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import javax.servlet.ServletException; import javax.servlet.annotation.MultipartConfig; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.Part; /** * * @author Barudisshu */ @MultipartConfig @WebServlet(name = "UploadServlet", urlPatterns = {"/UploadServlet"}) public class UploadServlet extends HttpServlet { /** * Processes requests for both HTTP * <code>GET</code> and * <code>POST</code> methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Part part = request.getPart("photo"); String fileName = getFileName(part); writeTo(fileName, part); } //取得上傳檔名 private String getFileName(Part part) { String header = part.getHeader("Content-Disposition"); String fileName = header.substring(header.indexOf("filename=\"") + 10, header.lastIndexOf("\"")); return fileName; } //儲存檔案 private void writeTo(String fileName, Part part) throws IOException, FileNotFoundException { InputStream in = part.getInputStream(); OutputStream out = new FileOutputStream("e:/workspace/" + fileName); byte[] buffer = new byte[1024]; int length = -1; while ((length = in.read(buffer)) != -1) { out.write(buffer, 0, length); } in.close(); out.close(); } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP * <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP * <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; } }
3、另一種較為簡單的方法:採用part的wirte(String fileName)上傳,瀏覽器將產生臨時TMP檔案
/**
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package net.individuals.web.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
/**
*採用part的wirte(String fileName)上傳,瀏覽器將產生臨時TMP檔案。
* @author Barudisshu
*/
@MultipartConfig(location = "e:/workspace")
@WebServlet(name = "UploadServlet", urlPatterns = {"/UploadServlet"})
public class UploadServlet extends HttpServlet {
/**
* Processes requests for both HTTP
* <code>GET</code> and
* <code>POST</code> methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//處理中文檔名
request.setCharacterEncoding("UTF-8");
Part part = request.getPart("photo");
String fileName = getFileName(part);
//將檔案寫入location指定的目錄
part.write(fileName);
}
private String getFileName(Part part) {
String header = part.getHeader("Content-Disposition");
String fileName = header.substring(header.indexOf("filename=\"") + 10, header.lastIndexOf("\""));
return fileName;
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP
* <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP
* <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
相關推薦
Servlet實現檔案上傳的幾種方法
1. 通過getInputStream()取得上傳檔案。 /** * To change this template, choose Tools | Templates * and open the template in the editor. */ package
js+jstl+servlet實現檔案上傳、列表展示及檔案下載
檔案上傳 1.upload.html: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert
servlet實現檔案上傳
一、Servlet實現檔案上傳,需要新增第三方提供的jar包 下載地址: 1) commons-fileupload-1.2.2-bin.zip : 點選開啟連結
Java Servlet實現檔案上傳並讀取Zip壓縮包中檔案的真實型別
1.上傳檔案servlet PS: 使用ant.jar中的 org.apache.tools.zip.ZipEntry 物件,防止亂碼 package com.chenl.servlets; import java.io.File; import java.io.IOExcep
Servlet實現檔案上傳詳解與實戰
檔案上傳 1.客戶端程式設計 要上傳檔案,必須利用mutipart/form-data 設定HTML表單的enctype 屬性值 <form action="action" enctype="mutipart/form-data" method="po
Jsp+Servlet實現檔案上傳下載——前臺頁面開發
JSP和Servlet都是J2EE的規範,JSP全名為Java Server Pages,中文名叫java伺服器頁面,它是在傳統的網頁HTML檔案中插入Java程式段(Scriptlet
檔案上傳五種方法對比
檔案上傳 這裡參考阮一峰老師的部落格,原文寫於2012年,現在需要不斷學習新東西。 早期不同檔案上傳瀏覽器相容性不好。現在HTML5出現後有了統一的介面。 1、早期 form 表單同步上傳 <form id="upload-form" action="upload.ph
Servlet實現檔案上傳的原理
Servlet 是用 Java 編寫的、協議和平臺都獨立的伺服器端元件,使用請求/響應的模式,提供了一個基於 Java 的伺服器解決方案。使用 Servlet 可以方便地處理在 HTML 頁面表單中提交的資料,但 Servlet 的 API 沒有提供對以 mutilpa
Servlet實現檔案上傳,可多檔案上傳
一、Servlet實現檔案上傳,需要新增第三方提供的jar包 下載地址: 接著把這兩個jar包放到 lib資料夾下: 二: 檔案上傳的表單提交方式必須是POST方式, 編碼型別:enctype="multipart/form-data",預設是 applicati
Servlet 實現檔案上傳
使用Servlet原生API進行檔案上傳: 一、Upload.java(檔案上傳Servlet) package servlet; import java.io.IOException; import java.io.InputStream; import java.ut
java實現檔案上傳下載的三種方法
JSP+Servlet 一、檔案上傳下載原理 在TCP/IP中,最早出現的檔案上傳機制是FTP。它是將檔案由客戶端傳送到伺服器的標準機制。但是在jsp程式設計中不能使用FTP方法來上傳檔案,這是由jsp的執行機制所決定的。 通過為表單元素設定Method=“post” en
ASP.NET MVC 檔案上傳和檔案下載 以及 檔案下載的幾種方法
1、序言最近專案中需要用到這個功能點,但是網上下載的時候總是出現亂碼。所以趁著這個時間自己整理出了一份,以後需要的時候就直接看自己的部落格就行了。已經測試過:在谷歌、火狐、IE等瀏覽器上都不會出現亂碼問題。2、結果展示2.1、上傳檔案成功介面 2.2、下載檔案成功介面3、上傳
selenium+python實現檔案上傳的方法(1)
檔案上傳 上傳檔案是比較常見的web端操作,但是在selenium的webdriver中沒有專門用於上傳的方法,下面介紹send_keys上傳方式實現上傳檔案 首先建立一個html檔案,主要實現上傳功能 upload file 頁面長這個樣子(每個瀏覽器裡頁面可能長得不一樣):
Java中實現檔案上傳下載的三種解決方案
第一點:Java程式碼實現檔案上傳 FormFile file=manform.getFile(); String newfileName = null; String newpathname=null; String fileAddre="/numU
jsp+servlet和SSM分別是如何實現檔案上傳(示例)
以下是jsp+servlet和SSM分別是如何實現檔案上傳的方法示例 兩種模式的upload.jsp檔案都一樣,(注意要加上enctype=”multipart/form-data”)如下: <
servlet+jquery實現檔案上傳進度條
現在檔案的上傳,特別是大檔案上傳,都需要進度條,讓客戶知道上傳進度。 本文簡單記錄下如何弄進度條,以及一些上傳資訊,比如檔案的大小,上傳速度,預計剩餘時間等一些相關資訊。程式碼是匆忙下簡單寫的,一些驗證沒做,或程式碼存在一些隱患,不嚴謹的地方。本文程
使用jsp/servlet簡單實現檔案上傳與下載
public class UploadServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,
Servlet 3.0改進的API 實現檔案上傳
1、Servlet 3.0 對檔案上傳的支援 Servlet 3.0 改進了部分API,使得java web 的開發進一步得到簡化。 其中兩個較大的改進是: HttpServletRequest 增加了對檔案上傳的支援 ServletContext 允許
Spring MVC 4使用Servlet 3 MultiPartConfigElement實現檔案上傳(帶原始碼)
package com.websystique.springmvc.controller; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; impor
DIV實現垂直居中的幾種方法
水平居中 好的 parent 間接 z-index -c 實現 解決 ble 說道垂直居中,我們首先想到的是vertical-align屬性,但是許多時候該屬性並不起作用。例如,下面的樣式並不能達到內容垂直居中顯示 1 div { 2 width:200px;