%--
Created by IntelliJ IDEA.
User: Lenovo
Date: 2020/6/19
Time: 22:53
Learn from https://www.bilibili.com/video/BV18z411i7gh?t=23p=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、表單中應(yīng)指定所提交的請求位multipart請求,通過在form/>標(biāo)簽中添加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>
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("當(dāng)前請求不支持文件上傳");
}
System.out.println("開始上傳文件");
//2、創(chuàng)建FileItem工廠==>文件寫入硬盤的作用
try {
DiskFileItemFactory factory = new DiskFileItemFactory();
//3、創(chuàng)建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、設(shè)置使用臨時文件的邊界值,大于該值,上傳文件先保存在臨時文件中,小于該值,則直接寫入內(nèi)存
//單位是字節(jié)
factory.setSizeThreshold(1024*1024*1);
//5、創(chuàng)建文件上傳核心組件
// 調(diào)用ServletFileUpload.parseRequest方法解析request對象,得到一個保存了所有上傳內(nèi)容的List對象。
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("utf-8");//可以解決文件名中文亂碼
upload.setFileSizeMax(1024*1024*2);
String bNo="defaultBNo",bName="defaultBName";
//6、解析請求
ListFileItem> 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對應(yīng)的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);
//獲取輸入流,其中有上傳文件的內(nèi)容
InputStream is = item.getInputStream();
//String path = this.getServletContext().getRealPath("/net/bookImage");//獲得當(dāng)前項目保存服務(wù)器地址,也就是web文件夾下
String path ="D:\\tomcat\\apache-tomcat-9.0.35-windows-x64\\apache-tomcat-9.0.35\\webapps\\librarySystem\\web\\net\\bookImage";
//文件夾內(nèi)文件數(shù)目有上限,但是可以創(chuàng)建子目錄
//獲取當(dāng)前系統(tǒng)時間
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;
//若該目錄不存在,直接創(chuàng)建新目錄
File dirFile = new File(path);
if(!dirFile.exists()){
dirFile.mkdirs();
}
//創(chuàng)建目標(biāo)文件,用來保存上傳文件
File desFile = new File(path,newFileName);
//創(chuàng)建文件輸出流
OutputStream os = new FileOutputStream(desFile);
//將輸入流數(shù)據(jù)寫入到輸出流中
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();
}
}
}
到此這篇關(guān)于jsp+servlet簡單實現(xiàn)上傳文件(保存目錄改進)的文章就介紹到這了,更多相關(guān)jsp servlet實現(xiàn)上傳文件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!