文章詳情頁
jsp+servlet簡單實現上傳文件功能(保存目錄改進)
1、jsp前端
<%-- Created by IntelliJ IDEA. User: Lenovo Date: 2020/6/19 Time: 22:53 Learn from https://www.bilibili.com/video/BV18z411i7gh?t=23&p=192 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>文件上傳</title> </head> <body> <!--文件上傳對表單的要求--> <!-- 1、表單中的請求提交方式必須是POST 2、表單中應指定所提交的請求位multipart請求,通過在<form/>標簽中添加enctype屬性 其值為multipart/form-data 3、 表單 --> <form method="POST" action="http://localhost:8888/hello/UploadImageServlet" enctype="multipart/form-data"> 編號<input type="text" name="BNO"></br> 名字<input type="text" name="BNAME"></br> 照片<input type="file" name="picutreUrl"></br> <input type="submit" value="注冊"> </form> </body> </html>
2、servlet后臺
package Servlet.bookServlet; 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; 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 java.io.*; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.List; @WebServlet(name = "UploadImageServlet") public class UploadImageServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request,response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //1、判斷請求是不是multipart請求 if(!ServletFileUpload.isMultipartContent(request)){ throw new RuntimeException("當前請求不支持文件上傳"); } System.out.println("開始上傳文件"); //2、創建FileItem工廠==>文件寫入硬盤的作用 try { DiskFileItemFactory factory = new DiskFileItemFactory(); //3、創建temp臨時文件夾 String tempPath ="D:\\tomcat\\apache-tomcat-9.0.35-windows-x64\\apache-tomcat-9.0.35\\webapps\\librarySystem\\web\\net\\temp"; File tempFile = new File(tempPath); factory.setRepository(tempFile); //4、設置使用臨時文件的邊界值,大于該值,上傳文件先保存在臨時文件中,小于該值,則直接寫入內存 //單位是字節 factory.setSizeThreshold(1024*1024*1); //5、創建文件上傳核心組件 // 調用ServletFileUpload.parseRequest方法解析request對象,得到一個保存了所有上傳內容的List對象。 ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding("utf-8");//可以解決文件名中文亂碼 upload.setFileSizeMax(1024*1024*2); String bNo="defaultBNo",bName="defaultBName"; //6、解析請求 List<FileItem> items =upload.parseRequest(request); //7、遍歷請求 for(FileItem item:items){ //普通表單項,上傳名字,編號等普通信息的上i傳 if(item.isFormField()){ String fileName = item.getFieldName();// name屬性值 String fileValue = item.getString("utf-8");// name對應的value值 System.out.println(fileName + " -- " + fileValue); if(fileName.equalsIgnoreCase("BNO")){ bNo = fileValue; } if(fileName.equalsIgnoreCase("BNAME")){ bName = fileValue; } } else{//上傳圖片等 String fileName = item.getName(); System.out.println("上傳文件名字:"+fileName); String suffix = fileName.substring(fileName.lastIndexOf("."));//獲取文件類型 String newFileName = bNo+"_"+bName+suffix; System.out.println(newFileName); //獲取輸入流,其中有上傳文件的內容 InputStream is = item.getInputStream(); //String path = this.getServletContext().getRealPath("/net/bookImage");//獲得當前項目保存服務器地址,也就是web文件夾下 String path ="D:\\tomcat\\apache-tomcat-9.0.35-windows-x64\\apache-tomcat-9.0.35\\webapps\\librarySystem\\web\\net\\bookImage"; //文件夾內文件數目有上限,但是可以創建子目錄 //獲取當前系統時間 Calendar now = Calendar.getInstance(); int year = now.get(Calendar.YEAR); int month = now.get(Calendar.MONTH)+1; int day = now.get(Calendar.DAY_OF_MONTH); path = path+"/"+year+"/"+month+"/"+day; //若該目錄不存在,直接創建新目錄 File dirFile = new File(path); if(!dirFile.exists()){ dirFile.mkdirs(); } //創建目標文件,用來保存上傳文件 File desFile = new File(path,newFileName); //創建文件輸出流 OutputStream os = new FileOutputStream(desFile); //將輸入流數據寫入到輸出流中 int len=-1; byte[]buf = new byte[1024]; while((len=is.read(buf))!=-1){ os.write(buf,0,len); } //desFile.delete();//刪除臨時文件 os.close();//輸出流 is.close();//輸入流 //刪除臨時文件 item.delete(); } } } catch (FileUploadException e) { e.printStackTrace(); } } }
總結
到此這篇關于jsp+servlet簡單實現上傳文件(保存目錄改進)的文章就介紹到這了,更多相關jsp servlet實現上傳文件內容請搜索以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持!
標簽:
JSP
相關文章:
排行榜
