本篇文章為大家展示了Java項目中使用 Servlet怎么實現(xiàn)一個文件分享功能,內(nèi)容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲。
創(chuàng)新互聯(lián)公司長期為上千多家客戶提供的網(wǎng)站建設(shè)服務(wù),團隊從業(yè)經(jīng)驗10年,關(guān)注不同地域、不同群體,并針對不同對象提供差異化的產(chǎn)品和服務(wù);打造開放共贏平臺,與合作伙伴共同營造健康的互聯(lián)網(wǎng)生態(tài)環(huán)境。為墊江企業(yè)提供專業(yè)的成都網(wǎng)站設(shè)計、做網(wǎng)站,墊江網(wǎng)站改版等技術(shù)服務(wù)。擁有十余年豐富建站經(jīng)驗和眾多成功案例,為您定制開發(fā)。
項目結(jié)構(gòu)
src com servletdemo DownloadServlet.java ShowServlet.java UploadServlet.java WebContent jsp servlet download.html fileupload.jsp input.jsp WEB-INF lib commons-fileupload-1.3.1.jar commons-io-2.4.jar
1.簡單實例
ShowServlet.java
package com.servletdemo; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class ShowServlet */ @WebServlet("/ShowServlet") public class ShowServlet extends HttpServlet { private static final long serialVersionUID = 1L; PrintWriter pw=null; /** * @see HttpServlet#HttpServlet() */ public ShowServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub this.doPost(request, response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub request.setCharacterEncoding("gb2312"); response.setContentType("text/html;charset=gb2312"); pw=response.getWriter(); String name=request.getParameter("username"); String password=request.getParameter("password"); pw.println("user name:" + name); pw.println("
"); pw.println("user password:" + password); } }
input.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>servlet demo
2.文件上傳實例
UploadServlet.java
package com.servletdemo; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.text.DateFormat; import java.util.Date; import java.util.List; import java.util.UUID; 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.ProgressListener; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; /** * Servlet implementation class UploadServlet */ @WebServlet("/servlet/UploadServlet") public class UploadServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public UploadServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub //設(shè)置編碼 request.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); PrintWriter pw = response.getWriter(); try { //設(shè)置系統(tǒng)環(huán)境 DiskFileItemFactory factory = new DiskFileItemFactory(); //文件存儲的路徑 String storePath = getServletContext().getRealPath("/WEB-INF/files"); //判斷傳輸方式 form enctype=multipart/form-data boolean isMultipart = ServletFileUpload.isMultipartContent(request); if(!isMultipart) { pw.write("傳輸方式有錯誤!"); return; } ServletFileUpload upload = new ServletFileUpload(factory); upload.setFileSizeMax(4*1024*1024);//設(shè)置單個文件大小不能超過4M upload.setSizeMax(4*1024*1024);//設(shè)置總文件上傳大小不能超過6M //監(jiān)聽上傳進度 upload.setProgressListener(new ProgressListener() { //pBytesRead:當前以讀取到的字節(jié)數(shù) //pContentLength:文件的長度 //pItems:第幾項 public void update(long pBytesRead, long pContentLength, int pItems) { System.out.println("已讀去文件字節(jié) :"+pBytesRead+" 文件總長度:"+pContentLength+" 第"+pItems+"項"); } }); //解析 Listitems = upload.parseRequest(request); for(FileItem item: items) { if(item.isFormField())//普通字段,表單提交過來的 { String name = item.getFieldName(); String value = item.getString("UTF-8"); System.out.println(name+"=="+value); }else { // String mimeType = item.getContentType(); 獲取上傳文件類型 // if(mimeType.startsWith("image")){ InputStream in =item.getInputStream(); String fileName = item.getName(); if(fileName==null || "".equals(fileName.trim())) { continue; } fileName = fileName.substring(fileName.lastIndexOf("\\")+1); fileName = UUID.randomUUID()+"_"+fileName; //按日期來建文件夾 String newStorePath = makeStorePath(storePath); String storeFile = newStorePath+"\\"+fileName; OutputStream out = new FileOutputStream(storeFile); byte[] b = new byte[1024]; int len = -1; while((len = in.read(b))!=-1) { out.write(b,0,len); } in.close(); out.close(); item.delete();//刪除臨時文件 } } // } }catch(org.apache.commons.fileupload.FileUploadBase.FileSizeLimitExceededException e){ //單個文件超出異常 pw.write("單個文件不能超過4M"); }catch(org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException e){ //總文件超出異常 pw.write("總文件不能超過6M"); }catch (FileUploadException e) { e.printStackTrace(); } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } private String makeStorePath(String storePath) { Date date = new Date(); DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM); String s = df.format(date); String path = storePath+"\\"+s; File file = new File(path); if(!file.exists()) { file.mkdirs();//創(chuàng)建多級目錄,mkdir只創(chuàng)建一級目錄 } return path; } private String makeStorePath3(String storePath, String fileName) { int hashCode = fileName.hashCode(); int dir1 = hashCode & 0xf;// 0000~1111:整數(shù)0~15共16個 int dir2 = (hashCode & 0xf0) >> 4;// 0000~1111:整數(shù)0~15共16個 String path = storePath + "\\" + dir1 + "\\" + dir2; // WEB-INF/files/1/12 File file = new File(path); if (!file.exists()) file.mkdirs(); return path; } }
fileupload.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %>Upload File Demo
3.文件下載實例
DownloadServlet.java
package com.servletdemo; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import java.net.URLEncoder; 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 javax.servlet.ServletResponse; /** * Servlet implementation class DownloadServlet */ @WebServlet("/DownloadServlet") public class DownloadServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public DownloadServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub download1(response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } public void download1(HttpServletResponse response) throws IOException{ //獲取所要下載文件的路徑 String path = this.getServletContext().getRealPath("/files/web配置.xml"); String realPath = path.substring(path.lastIndexOf("\\")+1); //告訴瀏覽器是以下載的方法獲取到資源 //告訴瀏覽器以此種編碼來解析URLEncoder.encode(realPath, "utf-8")) response.setHeader("content-disposition","attachment; filename="+URLEncoder.encode(realPath, "utf-8")); //獲取到所下載的資源 FileInputStream fis = new FileInputStream(path); int len = 0; byte [] buf = new byte[1024]; while((len=fis.read(buf))!=-1){ response.getOutputStream().write(buf,0,len); } } }
download.html
Download Demo download
上述內(nèi)容就是Java項目中使用 Servlet怎么實現(xiàn)一個文件分享功能,你們學到知識或技能了嗎?如果還想學到更多技能或者豐富自己的知識儲備,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。