程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> commons fileupload完成文件上傳的實例代碼

commons fileupload完成文件上傳的實例代碼

編輯:關於JAVA

commons fileupload完成文件上傳的實例代碼。本站提示廣大學習愛好者:(commons fileupload完成文件上傳的實例代碼)文章只能為提供參考,不一定能成為您想要的結果。以下是commons fileupload完成文件上傳的實例代碼正文


1、文件上傳的道理剖析

    1、文件上傳的需要條件

      a、表單的method必需是post

      b、表單的enctype屬性必需是multipart/form-data類型的。

      enctype默許值:application/x-www-form-urlencoded

      感化:告訴辦事器,要求注釋的MIME類型

      application/x-www-form-urlencoded : username=abc&password=123

      ServletRequest.getParameter(String name);該辦法是專門讀取該類型的辦法

      multipart/form-data:

    2、借助commons-fileupload組件完成文件的上傳

      a、拷貝jar包:commons-fileupload.jar commons-io.jar

      b、完成道理

    3、亂碼成績

      a、通俗字段的亂碼

        FileItem.getString(String charset);編碼要和客戶端分歧

      b、上傳的中文文件名亂碼

        request.setCharacterEncoding("UTF-8");編碼要和客戶端分歧

    4、詳細完成

前台upload.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">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<form action="${pageContext.request.contextPath}/servlet/UploadServlet3" method="post" enctype="multipart/form-data">
name:<input name="name"/><br/>
file1:<input type="file" name="f1"/><br/>
file2:<input type="file" name="f2"/><br/>
<input type="submit" value="上傳">
</form>
</body>
</html>

後台servlet代碼

package com.itheima.servlet;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
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.FileUploadBase;
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;
//詳解
public class UploadServlet3 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
System.out.print(request.getRemoteAddr());
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if(!isMultipart){
throw new RuntimeException("請檢討您的表單的enctype屬性,肯定是multipart/form-data");
}
DiskFileItemFactory dfif = new DiskFileItemFactory();
ServletFileUpload parser = new ServletFileUpload(dfif);
// parser.setFileSizeMax(3*1024*1024);//設置單個文件上傳的年夜小
// parser.setSizeMax(6*1024*1024);//多文件上傳時總年夜小限制
List<FileItem> items = null;
try {
items = parser.parseRequest(request);
}catch(FileUploadBase.FileSizeLimitExceededException e) {
out.write("上傳文件超越了3M");
return;
}catch(FileUploadBase.SizeLimitExceededException e){
out.write("總文件超越了6M");
return;
}catch (FileUploadException e) {
e.printStackTrace();
throw new RuntimeException("解析上傳內容掉敗,請從新試一下");
}
//處置要求內容
if(items!=null){
for(FileItem item:items){
if(item.isFormField()){
processFormField(item);
}else{
processUploadField(item);
}
}
}
out.write("上傳勝利!");
}
private void processUploadField(FileItem item) {
try {
String fileName = item.getName();
//用戶沒有選擇上傳文件時
if(fileName!=null&&!fileName.equals("")){
fileName = UUID.randomUUID().toString()+"_"+FilenameUtils.getName(fileName);
//擴大名
String extension = FilenameUtils.getExtension(fileName);
//MIME類型
String contentType = item.getContentType();
if(contentType.startsWith("image/")){
//分目次存儲:日期處理
// Date now = new Date();
// DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
// 
// String childDirectory = df.format(now);
//依照文件名的hashCode盤算存儲目次
String childDirectory = makeChildDirectory(getServletContext().getRealPath("/WEB-INF/files/"),fileName);
String storeDirectoryPath = getServletContext().getRealPath("/WEB-INF/files/"+childDirectory);
File storeDirectory = new File(storeDirectoryPath);
if(!storeDirectory.exists()){
storeDirectory.mkdirs();
}
System.out.println(fileName);
item.write(new File(storeDirectoryPath+File.separator+fileName));//刪除暫時文件
}
}
} catch (Exception e) {
throw new RuntimeException("上傳掉敗,請重試");
}
}
//盤算寄存的子目次
private String makeChildDirectory(String realPath, String fileName) {
int hashCode = fileName.hashCode();
int dir1 = hashCode&0xf;// 取1~4位
int dir2 = (hashCode&0xf0)>>4;//取5~8位
String directory = ""+dir1+File.separator+dir2;
File file = new File(realPath,directory);
if(!file.exists())
file.mkdirs();
return directory;
}
private void processFormField(FileItem item) {
String fieldName = item.getFieldName();//字段名
String fieldValue;
try {
fieldValue = item.getString("UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("不支撐UTF-8編碼");
}
System.out.println(fieldName+"="+fieldValue);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}

5、關於暫時文件成績

    a、DiskFileItemFactory

      public void setRepository(File repository):設置暫時文件的寄存目次
      public void setSizeThreshold(int sizeThreshold):設置緩存的年夜小

    b、     

      文件上傳時,本身用IO流處置,必定要在流封閉後刪除暫時文件。FileItem.delete()

      建議應用:FileItem.writer(File f).會主動刪除暫時文件。

    6、限制文件的年夜小

    a、 

      ServletFileUpload.setFileSizeMax(3*1024*1024);//設置單個文件上傳的年夜小

    b、

      ServletFileUpload.setSizeMax(6*1024*1024);//多文件上傳時總年夜小限制   

以上所述是小編給年夜家引見的commons fileupload完成文件上傳的實例代碼,願望對年夜家有所贊助,假如年夜家有任何疑問請給我留言,小編會實時答復年夜家的。在此也異常感激年夜家對網站的支撐!

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved