濮阳杆衣贸易有限公司

主頁 > 知識庫 > jsp+servlet簡單實現(xiàn)上傳文件功能(保存目錄改進)

jsp+servlet簡單實現(xiàn)上傳文件功能(保存目錄改進)

熱門標(biāo)簽:電話機器人銷售公司嗎 客服外呼系統(tǒng)呼叫中心 土地證宗地圖標(biāo)注符號 電話機器人案例 鎮(zhèn)江云外呼系統(tǒng)怎么樣 成都銷售外呼系統(tǒng)公司 自動外呼系統(tǒng)怎么防止封卡 vue 地圖標(biāo)注拖拽 保定電銷機器人軟件

1、jsp前端

%--
 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>

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("當(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();
    }
  }
}

總結(jié)

到此這篇關(guān)于jsp+servlet簡單實現(xiàn)上傳文件(保存目錄改進)的文章就介紹到這了,更多相關(guān)jsp servlet實現(xiàn)上傳文件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

您可能感興趣的文章:
  • JS pushlet XMLAdapter適配器用法案例解析
  • 如何將JSP/Servlet項目轉(zhuǎn)換為Spring Boot項目
  • Jsp+Servlet實現(xiàn)簡單登錄注冊查詢
  • JavaScript中ES6規(guī)范中l(wèi)et和const的用法和區(qū)別
  • jsp學(xué)習(xí)之scriptlet的使用方法詳解
  • 基于leaflet.js實現(xiàn)修改地圖主題樣式的流程分析
  • leaflet加載geojson疊加顯示功能代碼
  • JavaScript中l(wèi)et避免閉包造成問題

標(biāo)簽:內(nèi)江 成都 公主嶺 重慶 臺灣 麗江 天津 懷化

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《jsp+servlet簡單實現(xiàn)上傳文件功能(保存目錄改進)》,本文關(guān)鍵詞  jsp+servlet,簡單,實現(xiàn),上傳,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。
  • 相關(guān)文章
  • 下面列出與本文章《jsp+servlet簡單實現(xiàn)上傳文件功能(保存目錄改進)》相關(guān)的同類信息!
  • 本頁收集關(guān)于jsp+servlet簡單實現(xiàn)上傳文件功能(保存目錄改進)的相關(guān)信息資訊供網(wǎng)民參考!
  • 推薦文章
    新干县| 潜江市| 和顺县| 漳平市| 商丘市| 郧西县| 招远市| 和平县| 鄂伦春自治旗| 邹城市| 桓仁| 梧州市| 鄱阳县| 浪卡子县| 沁水县| 陆川县| 安岳县| 手游| 曲沃县| 彭阳县| 大余县| 漳平市| 武宁县| 师宗县| 祥云县| 通辽市| 柯坪县| 天等县| 江北区| 禄丰县| 宜昌市| 英山县| 高碑店市| 奇台县| 长顺县| 布拖县| 阿拉善右旗| 屯留县| 尤溪县| 景东| 龙岩市|