使用 commons-fileupload iframe 实现页面无刷新多文件上传

本文介绍了如何在Java中使用commons-fileupload-1.2.2.jar和commons-io-2.0.1.jar两个组件来实现文件上传功能,并通过一个简单的UploadServlet示例展示了其应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用了 commons-fileupload-1.2.2.jar 和 commons-io-2.0.1.jar 两个组件。

后台 UploadServlet.java:

package upload;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
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.SizeLimitExceededException;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

@SuppressWarnings("rawtypes")
public class UploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
request.setCharacterEncoding("UTF-8");
StringBuilder msg = new StringBuilder();
final long maxSize = 1000 * 1024 * 1024;
final String[] suffix = new String[] {"jpg", "jpeg", "gif", "txt", "doc","mp3", "wma", "m4a","rar","zip"};

File tmpdir = new File("c:/tmpdir");
if (!tmpdir.exists()) {
tmpdir.mkdirs();
}
File uploaddir = new File("c:/uploaddir");
if (!uploaddir.exists()) {
uploaddir.mkdirs();
}

DiskFileItemFactory fac = new DiskFileItemFactory(1024*4, tmpdir);

ServletFileUpload upload = new ServletFileUpload(fac);
upload.setSizeMax(maxSize);

List fileList = null;
try {
fileList = upload.parseRequest(request);
} catch (FileUploadException e) {
if (e instanceof SizeLimitExceededException) {
out.println("<script>parent.callback('" + " 文件尺寸超过 " + maxSize + " 最大限制 " + "')</script>");
return;
}
e.printStackTrace();
}

if (fileList.size() > 0) {
for (Iterator it = fileList.iterator(); it.hasNext();) {
String path = "";
String filename = null;
long size = 0;
String fileSuffix = null;
boolean has = false;
FileItem item = (FileItem) it.next();
if (item == null || item.isFormField()) {
continue;
}

path = item.getName();
int temp = path.lastIndexOf("\\");
filename = temp != -1 ? path.substring(temp + 1) : path;
size = item.getSize();
if (!path.equals("") && size != 0) {
fileSuffix = path.substring(path.lastIndexOf(".") + 1);

for (String s : suffix) {
if (s.equals(fileSuffix)) {
has = true;
break;
}
}
if (!has) {
msg.append(filename + " 上传文件格式不正确 ");
continue;
}
try {
item.write(new File(uploaddir + File.separator + filename));
msg.append(filename + " 上传成功 ");
} catch (Exception e) {
msg.append(filename + " 上传失败 ");
e.printStackTrace();
}
}
}
}
out.println("<script>parent.callback('" + msg.toString() + "')</script>");
}
}



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%>">

<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">
<script type="text/javascript">
function callback(msg)
{
/* document.getElementById("file").outerHTML = document.getElementById("file").outerHTML;*/
document.getElementById("msg").innerHTML = "<font color=red>"+msg+"</font>";
}
</script>
</head>

<body>
<form action="<%=path %>/UploadServlet" id="form1" name="form1" encType="multipart/form-data" method="post" target="hidden_frame" >
<input type="file" id="file" name="file" style="width:450"><br>
<input type="file" id="file" name="file" style="width:450"><br>
<input type="file" id="file" name="file" style="width:450"><br>
<input type="file" id="file" name="file" style="width:450"><br>
<input type="file" id="file" name="file" style="width:450"><br>
<input type="file" id="file" name="file" style="width:450"><br>
<INPUT type="submit" value="上传文件"><span id="msg"></span><br>
<font color="red">支持"jpg", "jpeg", "gif", "txt", "doc","mp3", "wma", "m4a","rar","zip"文件的上传</font>
<iframe name='hidden_frame' id="hidden_frame" style='display:none'></iframe>
</form>
</body>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值