JavaWeb文件上傳入門教程。本站提示廣大學習愛好者:(JavaWeb文件上傳入門教程)文章只能為提供參考,不一定能成為您想要的結果。以下是JavaWeb文件上傳入門教程正文
1、文件上傳道理
1、文件上傳的條件:
a、form表單的method必需是post
b、form表單的enctype必需是multipart/form-data(決議了POST要求方法,要求注釋的數據類型)
c、form中供給input的type是file類型的文件上傳域
2、應用第三方組件完成文件上傳
1、commons-fileupload組件:
jar:commons-fileupload.jar
commons-io.jar
2、焦點類或接口
DiskFileItemFactory:設置情況
public void setSizeThreshold(int sizeThreshold) :設置緩沖區年夜小。默許是10Kb。
當上傳的文件超越了緩沖區年夜小,fileupload組件將應用暫時文件緩存上傳文件
public void setRepository(java.io.File repository):設置暫時文件的寄存目次。默許是體系的暫時文件寄存目次。
ServletFileUpload:焦點上傳類(重要感化:解析要求的注釋內容)
boolean isMultipartContent(HttpServletRequest?request):斷定用戶的表單的enctype能否是multipart/form-data類型的。
List parseRequest(HttpServletRequest request):解析要求注釋中的內容
setFileSizeMax(4*1024*1024);//設置單個上傳文件的年夜小
upload.setSizeMax(6*1024*1024);//設置總文件年夜小
FileItem:代表表單中的一個輸出域。
boolean isFormField():能否是通俗字段
String getFieldName:獲得通俗字段的字段名
String getString():獲得通俗字段的值
InputStream getInputStream():獲得上傳字段的輸出流
String getName():獲得上傳的文件名
實例:先在WEB-INF目次下建一個files文件夾,也就是文件都要上傳到這裡,也是防止其別人直接拜訪
1.獲得files的真實途徑
String storePath = getServletContext().getRealPath("/WEB-INF/files");
2.設置情況
DiskFileItemFactory factory = new DiskFileItemFactory();//用默許的緩存和暫時文件存儲的處所
3.斷定表單傳送方法
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if(!isMultipart)
{
System.out.println("上傳方法毛病!");
return;
}
4.文件上傳焦點類
ServletFileUpload upload = new ServletFileUpload(factory);5.解析
//解析
List<FileItem> items = upload.parseRequest(request);
for(FileItem item: items)
{
if(item.isFormField()){//通俗字段,表單提交過去的
String fieldName = item.getFieldName();//表單信息的字段名
String fieldValue = item.getString(); //表單信息字段值
System.out.println(fieldName+"="+fieldValue);
}else//文件處置
{
InputStream in = item.getInputStream();
//上傳文件名 C:\Users\Administrator\Desktop\a.txt
String name = item.getName(); //只須要 a.txt
String fileName = name.substring(name.lastIndexOf("\\")+1);
//構建輸入流
String storeFile = storePath+"\\"+fileName;//上傳文件的保留地址
OutputStream out = new FileOutputStream(storeFile);
byte[] b = new byte[1024];
int len = -1;
while((len=in.read(b))!=-1)
{
out.write(b, 0, len);
}
in.close();//封閉流
out.close();
}
}
寫一個表單
<%@ 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%>">
<title>My JSP '1.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">
-->
</head>
<body>
<form action="${pageContext.request.contextPath}/servlet/UploadServlet2" method="post" enctype="multipart/form-data">
用戶名<input type="text" name="username"/> <br/>
<input type="file" name="f1"/><br/>
<input type="file" name="f2"/><br/>
<input type="submit" value="保留"/>
</form>
</body>
</html>
寫一個提交servlet:UploadServlet2
package com.liuzhen.upload;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
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;
//文件上傳入門案例
public class UploadServlet2 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//設置編碼
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
try {
//上傳文件的路徑
String storePath = getServletContext().getRealPath("/WEB-INF/files");
//設置情況
DiskFileItemFactory factory = new DiskFileItemFactory();
//斷定表單傳送方法 form enctype=multipart/form-data
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if(!isMultipart)
{
System.out.println("上傳方法毛病!");
return;
}
ServletFileUpload upload = new ServletFileUpload(factory);
//解析
List<FileItem> items = upload.parseRequest(request);
for(FileItem item: items)
{
if(item.isFormField()){//通俗字段,表單提交過去的
String fieldName = item.getFieldName();//表單信息的字段名
String fieldValue = item.getString(); //表單信息字段值
System.out.println(fieldName+"="+fieldValue);
}else//文件處置
{
InputStream in = item.getInputStream();
//上傳文件名 C:\Users\Administrator\Desktop\a.txt
String name = item.getName(); //只須要 a.txt
String fileName = name.substring(name.lastIndexOf("\\")+1);
//構建輸入流
String storeFile = storePath+"\\"+fileName;//上傳文件的保留地址
OutputStream out = new FileOutputStream(storeFile);
byte[] b = new byte[1024];
int len = -1;
while((len=in.read(b))!=-1)
{
out.write(b, 0, len);
}
in.close();//封閉流
out.close();
}
}
} catch (FileUploadException e) {
throw new RuntimeException(e);
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
上傳的文件是在Tomcat運用中。
以上就是本文的全體內容,願望對年夜家的進修有所贊助,也願望年夜家多多支撐。