java上传文件
上传文件
java
package com.exam;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
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.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class UploadPage
*/
public class UploadPage extends HttpServlet {
private static final long serialVersionUID = 1L;
// 上传文件存储目录
private static final String UPLOAD_DIRECTORY = "upload";
// 上传配置
private static final int MEMORY_THRESHOLD = 1024 * 1024 * 3; // 3MB
private static final int MAX_FILE_SIZE = 1024 * 1024 * 40; // 40MB
private static final int MAX_REQUEST_SIZE = 1024 * 1024 * 50; // 50MB
ServletContext servletContext = null;
/**
* @see Servlet#init(ServletConfig)
*/
public void init(ServletConfig config) throws ServletException {
// TODO Auto-generated method stub
servletContext = config.getServletContext();
}
/**
* @see Servlet#destroy()
*/
public void destroy() {
// TODO Auto-generated method stub
}
/**
* @see HttpServlet#service(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
// 检测是否为多媒体上传
if (!ServletFileUpload.isMultipartContent(request)) {
// 如果不是则停止
PrintWriter writer = response.getWriter();
writer.println("Error: 表单必须包含 enctype=multipart/form-data");
writer.flush();
return;
}
// 配置上传参数
DiskFileItemFactory factory = new DiskFileItemFactory();
// 设置内存临界值 - 超过后将产生临时文件并存储于临时目录中
factory.setSizeThreshold(MEMORY_THRESHOLD);
// 设置临时存储目录
factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
ServletFileUpload upload = new ServletFileUpload(factory);
// 设置最大文件上传值
upload.setFileSizeMax(MAX_FILE_SIZE);
// 设置最大请求值 (包含文件和表单数据)
upload.setSizeMax(MAX_REQUEST_SIZE);
// 中文处理
upload.setHeaderEncoding("UTF-8");
// 构造临时路径来存储上传的文件
// 这个路径相对当前应用的目录
String uploadPath = servletContext.getRealPath("/WEB-INF/") + File.separator + UPLOAD_DIRECTORY;
// 如果目录不存在则创建
File uploadDir = new File(uploadPath);
if (!uploadDir.exists()) {
uploadDir.mkdir();
}
try {
// 解析请求的内容提取文件数据
@SuppressWarnings("unchecked")
List<FileItem> formItems = upload.parseRequest(request);
if (formItems != null && formItems.size() > 0) {
// 迭代表单数据
for (FileItem item : formItems) {
// 处理不在表单中的字段
if (!item.isFormField()) {
String fileName = new File(item.getName()).getName();
String filePath = uploadPath + File.separator + fileName;
File storeFile = new File(filePath);
// 在控制台输出文件的上传路径
System.out.println(filePath);
// 保存文件到硬盘
item.write(storeFile);
request.setAttribute("message", "文件"+filePath+"上传成功!");
}
}
}
} catch (Exception ex) {
request.setAttribute("message", "错误信息: " + ex.getMessage());
}
// 跳转到 message.jsp
servletContext.getRequestDispatcher("/message.jsp").forward(request, response);
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="stylesheet" href="css/upload.css">
<title>upload</title>
</head>
<body>
<div id="wrap">
<h1>UPLOAD A FILE</h1>
<br><br><br>
<div id="form-wrap">
<form method="post" action="/examination/UploadPage"
enctype="multipart/form-data">
<p>HELLO</p>
<label for="email">Choose A File</label>
<textarea name="message" id="message" value="Your Message"></textarea>
<p>Move here ,</p>
<label for="name">File Name</label>
<input type="file" name="uploadFile" />
<label for="email" style="margin-left: -60px">Replace Name:</label>
<input type="text" name="replacename" value="" id="email" />
<input type="submit" name="submit" value="NOW, UPLOAD YOUR FILE!" />
</form>
</div>
</div>
</body>
</html>
css
@CHARSET "UTF-8";
body, div, h1, h2, form, fieldset, input, textarea, footer, p{
margin: 0;
padding: 0;
border: 0;
outline: none;
}
body{
background: pink;
color: gray;
font-family: tahoma;
}
p{
font-family: tahoma;
font-size: 24px;
color: #757575;
}
#wrap{
width: 530px;
margin: 20px auto 0;
height: 1000px;
}
h1{
margin-bottom: 20px;
text-align: center;
font-size: 35px;
font-family: tahoma;
color: black;
}
#form-wrap{
overflow: hidden;
height: 447px;
position: relative;
top: 0px;
transition: all 1s ease-in-out .3s;
}
#form-wrap:before{
content: "";
position: absolute;
bottom: 128px;
left: 0px;
background: url('../img/before.png');
width: 530px;
height: 317px;
}
#form-wrap:after{
content: "";
position: absolute;
bottom: 0px;
left: 0;
background: url('../img/after.png');
width: 530px;
height: 259px;
}
#form-wrap.hide:after,
#form-wrap.hide:before{
display: none;
}
#form-wrap:hover{
height: 777px;
top: -200px;
}
form{
background: url('../img/letter_bg.png');
position: relative;
top: 200px;
overflow: hidden;
height: 200px;
width: 400px;
margin: 0px auto;
padding: 20px;
border: 1px solid white;
border-right: 3px;
transition: all 1s ease-in-out .3s;
}
#form-wrap:hover form{
height: 530px;
}
lable{
margin: 11px 20px 0 0;
font-size: 15px;
color: gray;
text-transform: uppercase;
}
input[type=text], textarea{
font: 14px normal uppercase, arial, serif;
color: dimgray;
background: none;
width: 380px;
height: 37px;
padding: 0px 10px;
margin: 0 0 10px 0;
border: 1px solid #BDBDBD;
border-radius: 5px;
}
textarea{
height: 80px;
padding-top: 14px;
}
textarea:focus,
input[type=text]:focus{
background: url('../img/letter_bg.png');
}
#form-wrap input[type=submit]{
position: relative;
font-family: tahoma;
font-size: 24px;
color: gray;
width: 300px;
text-align: center;
opacity: 0;
background: none;
cursor: pointer;
border-radius: 3px;
transition: opacity 0.7s ease-in-out 0s;
}
#form-wrap:hover input[type=submit]{
z-index: 1;
opacity: 1;
transition: opacity 0.5s ease-in-out 1.3s;
}
本文来自博客园,作者:没有烦恼的猫猫,转载请注明原文链接:https://www.cnblogs.com/maomao777/p/16036219.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)