JavaWeb文件上傳入門教程
一、文件上傳原理
1、文件上傳的前提:
a、form表單的method必須是post
b、form表單的enctype必須是multipart/form-data(決定了POST請(qǐng)求方式,請(qǐng)求正文的數(shù)據(jù)類型)
c、form中提供input的type是file類型的文件上傳域
二、利用第三方組件實(shí)現(xiàn)文件上傳
1、commons-fileupload組件:
jar:commons-fileupload.jar
commons-io.jar
2、核心類或接口
DiskFileItemFactory:設(shè)置環(huán)境
public void setSizeThreshold(int sizeThreshold) :設(shè)置緩沖區(qū)大小。默認(rèn)是10Kb。
當(dāng)上傳的文件超出了緩沖區(qū)大小,fileupload組件將使用臨時(shí)文件緩存上傳文件
public void setRepository(java.io.File repository):設(shè)置臨時(shí)文件的存放目錄。默認(rèn)是系統(tǒng)的臨時(shí)文件存放目錄。
ServletFileUpload:核心上傳類(主要作用:解析請(qǐng)求的正文內(nèi)容)
boolean isMultipartContent(HttpServletRequest?request):判斷用戶的表單的enctype是否是multipart/form-data類型的。
List parseRequest(HttpServletRequest request):解析請(qǐng)求正文中的內(nèi)容
setFileSizeMax(4*1024*1024);//設(shè)置單個(gè)上傳文件的大小
upload.setSizeMax(6*1024*1024);//設(shè)置總文件大小
FileItem:代表表單中的一個(gè)輸入域。
boolean isFormField():是否是普通字段
String getFieldName:獲取普通字段的字段名
String getString():獲取普通字段的值
InputStream getInputStream():獲取上傳字段的輸入流
String getName():獲取上傳的文件名
實(shí)例:先在WEB-INF目錄下建一個(gè)files文件夾,也就是文件都要上傳到這里,也是避免其他人直接訪問
1.獲取files的真實(shí)路徑
String storePath = getServletContext().getRealPath("/WEB-INF/files");
2.設(shè)置環(huán)境
DiskFileItemFactory factory = new DiskFileItemFactory();//用默認(rèn)的緩存和臨時(shí)文件存儲(chǔ)的地方
3.判斷表單傳送方式
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if(!isMultipart)
{
System.out.println("上傳方式錯(cuò)誤!");
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);
//構(gòu)建輸出流
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();//關(guān)閉流
out.close();
}
}
寫一個(gè)表單
<%@ 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>
寫一個(gè)提交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 {
//設(shè)置編碼
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
try {
//上傳文件的路徑
String storePath = getServletContext().getRealPath("/WEB-INF/files");
//設(shè)置環(huán)境
DiskFileItemFactory factory = new DiskFileItemFactory();
//判斷表單傳送方式 form enctype=multipart/form-data
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if(!isMultipart)
{
System.out.println("上傳方式錯(cuò)誤!");
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);
//構(gòu)建輸出流
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();//關(guān)閉流
out.close();
}
}
} catch (FileUploadException e) {
throw new RuntimeException(e);
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
上傳的文件是在Tomcat應(yīng)用中。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- Javaweb基礎(chǔ)入門requse原理與使用
- JavaWeb入門:HttpResponse和HttpRequest詳解
- JavaWeb入門:ServletContext詳解和應(yīng)用
- JavaWeb 入門:Hello Servlet
- JavaWeb 入門篇:創(chuàng)建Web項(xiàng)目,Idea配置tomcat
- JavaWeb入門教程之分頁查詢功能的簡(jiǎn)單實(shí)現(xiàn)
- javaWeb使用servlet搭建服務(wù)器入門
- C程序函數(shù)調(diào)用&系統(tǒng)調(diào)用
- Javaweb基礎(chǔ)入門HTML之table與form
相關(guān)文章
IDEA 2020.2 部署JSF項(xiàng)目的詳細(xì)過程
本文通過圖文并茂的形式教大家如何在IDEA中創(chuàng)建一個(gè)JSF項(xiàng)目及遇到問題的解決方法,感興趣的朋友跟隨小編一起看看吧2021-09-09
使用Java實(shí)現(xiàn)價(jià)格加密與優(yōu)化功能
在現(xiàn)代軟件開發(fā)中,數(shù)據(jù)加密是一個(gè)非常重要的環(huán)節(jié),尤其是在處理敏感信息(如價(jià)格、用戶數(shù)據(jù)等)時(shí),本文將詳細(xì)介紹如何使用?Java?實(shí)現(xiàn)價(jià)格加密,并對(duì)代碼進(jìn)行優(yōu)化,需要的朋友可以參考下2025-01-01
程序包org.springframework不存在的解決辦法
這篇文章主要介紹了程序包org.springframework不存在的解決辦法,在使用IDEA創(chuàng)建SpringBoot項(xiàng)目時(shí),剛打開無法正常運(yùn)行,本文通過圖文結(jié)合的方式給大家介紹的非常詳細(xì),具有一定參考價(jià)值,需要的朋友可以參考下2024-07-07
Mybatis中的resultType和resultMap使用
這篇文章主要介紹了Mybatis中的resultType和resultMap使用,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-09-09
java程序運(yùn)行時(shí)內(nèi)存分配詳解
這篇文章主要介紹了java程序運(yùn)行時(shí)內(nèi)存分配詳解 ,需要的朋友可以參考下2016-07-07
MyBatis實(shí)現(xiàn)簡(jiǎn)單的數(shù)據(jù)表分月存儲(chǔ)
本文主要介紹了MyBatis實(shí)現(xiàn)簡(jiǎn)單的數(shù)據(jù)表分月存儲(chǔ),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-03-03

