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

javaweb實(shí)現(xiàn)文件上傳示例代碼

 更新時間:2017年04月08日 15:55:19   作者:第九種格調(diào)的人生  
這篇文章主要為大家詳細(xì)介紹了javaweb實(shí)現(xiàn)文件上傳的示例代碼,具有一定的參考價值,感興趣的小伙伴們可以參考一下

本文實(shí)例為大家分享了javaweb文件下載的具體實(shí)現(xiàn)代碼,供大家參考,具體內(nèi)容如下

文件上傳示例

注意:jsp頁面編碼為"UTF-8"

文件上傳的必要條件

1.form表單,必須為POST方式提交

2.enctype="multipart/form-data"

3.必須有<input type="file" />

前端jsp頁面

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
 <head>
 <base href="<%=basePath%>" rel="external nofollow" >
 
 <title>My JSP 'index.jsp' starting page</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">
 <!--
 <link rel="stylesheet" type="text/css" href="styles.css" rel="external nofollow" >
 -->
 </head>
 <script type="text/javascript">
  function addFile(){
   var div1=document.getElementById("div1");
   div1.innerHTML+="<div><input type='file' /><input type='button' value='刪除' onclick='deleteFile(this)' /> 
</div>";
  
  }
  function deleteFile(div){
   div.parentNode.parentNode.removeChild(div.parentNode);
  
  }
 </script>
 <body>
  <form action="${pageContext.request.contextPath }/servlet/upLoadServlet" method="post" enctype="multipart/form-data">
  文件的描述:<input type="text" name ="description" />

  <div id="div1">
   <div>
   <input type="file" name ="file" /><input type="button" value="添加" onclick="addFile()" />

   </div>   
  </div> 
   <input type="submit" />
  </form>
 </body>
</html>

實(shí)現(xiàn)文件上傳的servlet

package com.learning.servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
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.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;

/**
 * Servlet implementation class UpLoadServlet
 */
@WebServlet("/servlet/upLoadServlet")
public class UpLoadServlet extends HttpServlet {
 private static final long serialVersionUID = 1L;

 /**
  * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
  */
 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  doGet(request, response);
 }

 /**
  * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
  */
 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
   
  
  //文件上傳
  //判斷是否支持文件上傳
  boolean isMultipartContent = ServletFileUpload
    .isMultipartContent(request);
  if (!isMultipartContent) {
   throw new RuntimeException("不支持");
  }
  
  // 創(chuàng)建一個DiskFileItemfactory工廠類
  DiskFileItemFactory diskFileItemFactory=new DiskFileItemFactory();
  // 創(chuàng)建一個ServletFileUpload核心對象
  ServletFileUpload fileUpload=new ServletFileUpload(diskFileItemFactory);
  //設(shè)置中文亂碼
  fileUpload.setHeaderEncoding("UTF-8");
  //設(shè)置一個文件大小
  fileUpload.setFileSizeMax(1024*1024*3); //大小為3M
  //設(shè)置總文件大小
  //fileUpload.setSizeMax(1024*1024*10);//大小為10M
  
  try {
   //fileload解析request請求,返回list<FileItem>集合
   List<FileItem> fileItems = fileUpload.parseRequest(request);
   for (FileItem fileItem : fileItems) {
    if (fileItem.isFormField()) {
     //是文本域 (處理文本域的函數(shù))
     processFormField(fileItem);
    }else {
     //文件域 (處理文件域的函數(shù))
     processUpLoadField1(fileItem);
    }
   }
   
  } catch (FileUploadException e) {
   e.printStackTrace();
  }
  
  
 }

 /**
  * @param fileItem
  * 
  */
 private void processUpLoadField1(FileItem fileItem) {
  
  try {
   //獲得文件讀取流
   InputStream inputStream = fileItem.getInputStream();
   
   //獲得文件名
   String fileName = fileItem.getName();
   
   //對文件名處理
   if (fileName!=null) {
    fileName.substring(fileName.lastIndexOf(File.separator)+1);
    
   }else {
    throw new RuntimeException("文件名不存在");
   }
   
   //對文件名重復(fù)處理
//   fileName=new String(fileName.getBytes("ISO-8859-1"),"UTF-8");
   fileName=UUID.randomUUID()+"_"+fileName;
   
   //日期分類
   SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
   String date = simpleDateFormat.format(new Date());
   //創(chuàng)建目錄
   File parent=new File(this.getServletContext().getRealPath("/WEB-INF/upload/"+date));
   if (!parent.exists()) {
    parent.mkdirs();
   }
   
   //上傳文件
   fileItem.write(new File(parent, fileName));
   //刪除臨時文件(如果上傳文件過大,會產(chǎn)生.tmp的臨時文件)
   fileItem.delete();
   
  } catch (IOException e) {
   System.out.println("上傳失敗");
   e.printStackTrace();
  } catch (Exception e) {
   
  }
  
  
  
 }

 /**
  * @param fileItem
  */
 //文件域
 private void processUpLoadField(FileItem fileItem) {
   
  try {
   //獲得文件輸入流
   InputStream inputStream = fileItem.getInputStream();
   
   //獲得是文件名字
   String filename = fileItem.getName();
   //對文件名字處理
   if (filename!=null) {
//    filename.substring(filename.lastIndexOf(File.separator)+1);
    filename = FilenameUtils.getName(filename);
   }
   
   //獲得路徑,創(chuàng)建目錄來存放文件
   String realPath = this.getServletContext().getRealPath("/WEB-INF/load");
   
   File storeDirectory=new File(realPath);//既代表文件又代表目錄
   //創(chuàng)建指定目錄
   if (!storeDirectory.exists()) {
    storeDirectory.mkdirs();
   }
   //防止文件名一樣
   filename=UUID.randomUUID()+"_"+filename;
   //目錄打散 防止同一目錄文件下文件太多,不好查找
   
   //按照日期分類存放上傳的文件
   //storeDirectory = makeChildDirectory(storeDirectory);
   
   //多級目錄存放上傳的文件
   storeDirectory = makeChildDirectory(storeDirectory,filename);
   
   FileOutputStream fileOutputStream=new FileOutputStream(new File(storeDirectory, filename));
   //讀取文件,輸出到指定的目錄中
   int len=1;
   byte[] b=new byte[1024];
   while((len=inputStream.read(b))!=-1){
    fileOutputStream.write(b, 0, len);
   }
   //關(guān)閉流
   fileOutputStream.close();
   inputStream.close(); 
   
  } catch (IOException e) {
   e.printStackTrace();
  } 
 }
 //按照日期來分類
 private File makeChildDirectory(File storeDirectory) {
  SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
  String date = simpleDateFormat.format(new Date());
  //創(chuàng)建目錄
  File childDirectory=new File(storeDirectory, date);
  if (!childDirectory.exists()) {
   childDirectory.mkdirs();
  }
  return childDirectory;
 } 
 //多級目錄
 private File makeChildDirectory(File storeDirectory, String filename) {
  filename=filename.replaceAll("-", ""); 
  File childDirectory =new File(storeDirectory, filename.charAt(0)+File.separator+filename.charAt(1));
  if (!childDirectory.exists()) {
   childDirectory.mkdirs();  
  }
  return childDirectory;
 }
 //文本域
 private void processFormField(FileItem fileItem) {
  //對于文本域的中文亂碼,可以用new String()方式解決
   try {
    String fieldName = fileItem.getFieldName();//表單中字段名name,如description
    String fieldValue = fileItem.getString("UTF-8");//description中value
//    fieldValue=new String(fieldValue.getBytes("ISO-8859-1"),"UTF-8");
    System.out.println(fieldName +":"+fieldValue);
   } catch (UnsupportedEncodingException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
   
 }

}

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • spring?security?自定義Provider?如何實(shí)現(xiàn)多種認(rèn)證

    spring?security?自定義Provider?如何實(shí)現(xiàn)多種認(rèn)證

    這篇文章主要介紹了spring?security?自定義Provider實(shí)現(xiàn)多種認(rèn)證方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-12-12
  • Java設(shè)計模式之觀察者模式原理與用法詳解

    Java設(shè)計模式之觀察者模式原理與用法詳解

    這篇文章主要介紹了Java設(shè)計模式之觀察者模式,結(jié)合實(shí)例形式詳細(xì)分析了Java設(shè)計模式之觀察者模式基本概念、原理、用法及操作注意事項,需要的朋友可以參考下
    2020-06-06
  • Spring MVC 4.1.3 + MyBatis零基礎(chǔ)搭建Web開發(fā)框架(注解模式)

    Spring MVC 4.1.3 + MyBatis零基礎(chǔ)搭建Web開發(fā)框架(注解模式)

    本篇文章主要介紹了Spring MVC 4.1.3 + MyBatis零基礎(chǔ)搭建Web開發(fā)框架(注解模式),具有一定的參考價值,感興趣的小伙伴們可以參考一下。
    2017-03-03
  • SpringBoot配置攔截器的示例

    SpringBoot配置攔截器的示例

    這篇文章主要介紹了SpringBoot配置攔截器的示例,幫助大家更好的理解和使用springboot框架,感興趣的朋友可以了解下
    2020-11-11
  • RocketMQ保證消息的有序性的案例分享

    RocketMQ保證消息的有序性的案例分享

    Apache RocketMQ 是一個常用的開源消息中間件,它提供了強(qiáng)大的有序消息處理能力,這里我們會探討 RocketMQ 是如何保證消息的有序性的,包括其設(shè)計原理和相關(guān)的源碼實(shí)現(xiàn),需要的朋友可以參考下
    2024-04-04
  • 淺談利用Session防止表單重復(fù)提交

    淺談利用Session防止表單重復(fù)提交

    這篇文章主要介紹了淺談利用Session防止表單重復(fù)提交,簡單介紹表單重復(fù)提交的情況,分析,以及解決方法代碼示例,具有一定借鑒價值,需要的朋友可以了解下。
    2017-12-12
  • Java獲取json數(shù)組對象的實(shí)例講解

    Java獲取json數(shù)組對象的實(shí)例講解

    下面小編就為大家分享一篇Java獲取json數(shù)組對象的實(shí)例講解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-03-03
  • SpringBoot--Banner的定制和關(guān)閉操作

    SpringBoot--Banner的定制和關(guān)閉操作

    這篇文章主要介紹了SpringBoot--Banner的定制和關(guān)閉操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2018-05-05
  • Java8中流的性能及流的幾個特性

    Java8中流的性能及流的幾個特性

    流(Stream)是Java8為了實(shí)現(xiàn)最佳性能而引入的一個全新的概念。接下來通過本文給大家分享Java8中流的性能,需要的朋友參考下吧
    2017-11-11
  • SpringBoot 簽到獎勵實(shí)現(xiàn)方案的示例代碼

    SpringBoot 簽到獎勵實(shí)現(xiàn)方案的示例代碼

    這篇文章主要介紹了SpringBoot 簽到獎勵實(shí)現(xiàn)方案的示例代碼,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-08-08

最新評論