欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

java文件上傳Demo(必看篇)

 更新時間:2017年05月11日 07:46:28   投稿:jingxian  
下面小編就為大家?guī)硪黄猨ava文件上傳Demo(必看篇)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

說到文件上傳我們要做到:

1.引入兩個包:commons-fileupload-1.2.1.jar和commons-io-1.3.2.jar

2.將form改為上傳文件模式:enctype="multipart/form-data"

3.開始編寫相關(guān)代碼

這里會用到幾個關(guān)鍵的類:磁盤文件工廠DiskFileItemFactory ; 創(chuàng)建servlet文件上傳類:ServletFileUpload

還有幾個重要的方法:DiskFileItemFactory類用于將以臨時文件形式保存在磁盤上的存放目錄的方法setRepository;

ServletFileUpload類得到表單中所有的數(shù)據(jù),得到form表單中所有的元素方法:parseRequest

下面看具體代碼:

說明以這種方式上傳文件是保存在服務(wù)器端的!

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
 
import javax.servlet.ServletException;
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.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;
 
 
public class UploadServlet extends HttpServlet {
 
  /**
   * Constructor of the object.
   */
  public UploadServlet() {
    super();
  }
 
  /**
   * Destruction of the servlet. <br>
   */
  public void destroy() {
    super.destroy(); // Just puts "destroy" string in log
    // Put your code here
  }
 
  /**
   * The doGet method of the servlet. <br>
   *
   * This method is called when a form has its tag value method equals to get.
   *
   * @param request the request send by the client to the server
   * @param response the response send by the server to the client
   * @throws ServletException if an error occurred
   * @throws IOException if an error occurred
   */
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
 
    this.doPost(request, response);
  }
 
  /**
   * The doPost method of the servlet. <br>
   *
   * This method is called when a form has its tag value method equals to post.
   *
   * @param request the request send by the client to the server
   * @param response the response send by the server to the client
   * @throws ServletException if an error occurred
   * @throws IOException if an error occurred
   */
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
 
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    DiskFileItemFactory sf= new DiskFileItemFactory();//實例化磁盤被文件列表工廠
    String path = request.getRealPath("/upload");//得到上傳文件的存放目錄
    sf.setRepository(new File(path));//設(shè)置文件存放目錄
    sf.setSizeThreshold(1024*1024);//設(shè)置文件上傳小于1M放在內(nèi)存中
    String rename = "";//文件新生成的文件名
    String fileName = "";//文件原名稱
    String name = "";//普通field字段
    //從工廠得到servletupload文件上傳類
    ServletFileUpload sfu = new ServletFileUpload(sf);
     
    try {
      List<FileItem> lst = sfu.parseRequest(request);//得到request中所有的元素
      for (FileItem fileItem : lst) {
        if(fileItem.isFormField()){
          if("name".equals(fileItem.getFieldName())){
            name = fileItem.getString("UTF-8");
          }
        }else{
          //獲得文件名稱
          fileName = fileItem.getName();
          fileName = fileName.substring(fileName.lastIndexOf("\\")+1);
          String houzhui = fileName.substring(fileName.lastIndexOf("."));
          rename = UUID.randomUUID()+houzhui;
          fileItem.write(new File(path, rename));
        }
      }
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
     
    System.out.println("普通字段"+name);
    System.out.println("文件名稱"+fileName);
    System.out.println("修改后生成的文件名稱"+rename);
    response.sendRedirect("ok.jsp");
    out.flush();
    out.close();
  }
 
  /**
   * Initialization of the servlet. <br>
   *
   * @throws ServletException if an error occurs
   */
  public void init() throws ServletException {
    // Put your code here
  }
 
}

index.jsp頁面:

 

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
 <head>  
  <title>文件測試界面</title>
  <meta http-equiv="pragma" content="no-cache">
  <meta http-equiv="cache-control" content="no-cache">
  <meta http-equiv="expires" content="0">  
  <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
  <meta http-equiv="description" content="This is my page">
 </head>
 <body>
  <div align="center">
  <form action="UploadServlet" enctype="multipart/form-data" method="post">
    名稱:<input name="name" /> <br>
    圖片:<input name="img" type="file"/><br>
    <input type="submit" value="提交" />  
    <input type="reset" value="重置" />
  </form>
  </div>
 </body>
</html>

ok.jsp頁面:

<body>
  <h1 align="center">上傳文件成功!</h1>
 </body>

實現(xiàn)效果就不截圖了,有需要自己那過去用!

以上這篇java文件上傳Demo(必看篇)就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • 如何用java計算兩個時間相差多少小時

    如何用java計算兩個時間相差多少小時

    最近工作中遇到需要計算時間差,下面這篇文章主要給大家介紹了關(guān)于如何用java計算兩個時間相差多少小時的相關(guān)資料,文中通過示例代碼介紹的非常詳細,需要的朋友可以參考下
    2022-12-12
  • Java的動態(tài)代理模式之JDK代理詳解

    Java的動態(tài)代理模式之JDK代理詳解

    這篇文章主要介紹了Java的動態(tài)代理模式之JDK代理詳解,代理對象,不需要實現(xiàn)接口,但是目標對象要實現(xiàn)接口,否則不能用動態(tài)代理,JDK?實現(xiàn)代理只需要使用?newProxyInstance?方法,但是該方法需要接收三個參數(shù),需要的朋友可以參考下
    2023-11-11
  • 詳細介紹Spring的配置文件

    詳細介紹Spring的配置文件

    這篇文章主要為大家詳細介紹了Spring中的配置文件的命名以及它的配置文件都有些什么。文中的示例代碼講解詳細,感興趣的小伙伴可以跟上小編一起學習一下
    2022-10-10
  • Spring Boot 快速集成 Redis的方法

    Spring Boot 快速集成 Redis的方法

    這篇文章主要介紹了Spring Boot 如何快速集成 Redis,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-07-07
  • Java 實現(xiàn)跨平臺的操作方式

    Java 實現(xiàn)跨平臺的操作方式

    這篇文章主要介紹了Java 實現(xiàn)跨平臺的操作方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-09-09
  • java項目啟動失敗的問題及解決

    java項目啟動失敗的問題及解決

    這篇文章主要介紹了java項目啟動失敗的問題及解決方案,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-06-06
  • 深入理解Java設(shè)計模式之原型模式

    深入理解Java設(shè)計模式之原型模式

    這篇文章主要介紹了JAVA設(shè)計模式之原型模式的的相關(guān)資料,文中示例代碼非常詳細,供大家參考和學習,感興趣的朋友可以了解下
    2021-11-11
  • 通過Java代碼來創(chuàng)建view的方法

    通過Java代碼來創(chuàng)建view的方法

    本文給大家分享通過java代碼創(chuàng)建view的方法,以TextView為例創(chuàng)建控件的方法,需要的的朋友參考下吧
    2017-08-08
  • springboot如何根據(jù)不同的日志級別顯示不同的顏色

    springboot如何根據(jù)不同的日志級別顯示不同的顏色

    這篇文章主要介紹了springboot如何根據(jù)不同的日志級別顯示不同的顏色問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2023-08-08
  • 詳解使用MyBatis Generator自動創(chuàng)建代碼

    詳解使用MyBatis Generator自動創(chuàng)建代碼

    這篇文章主要介紹了使用MyBatis Generator自動創(chuàng)建代碼,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-12-12

最新評論