java jakata commons上传

本文介绍了一个使用Java实现的文件上传处理程序,通过Servlet和Apache Commons FileUpload库来处理HTTP请求中的文件上传。该程序设置了文件大小限制、临时存储路径,并通过正则表达式筛选文件类型。

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

upload.java

import java.io.File;

import java.io.IOException;

import java.io.PrintWriter;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
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.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 Upload extends HttpServlet {


private static final long serialVersionUID = 1L;



public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

// 解决中文乱码

String encoding="utf-8";

request.setCharacterEncoding(encoding);

response.setContentType("text/html; charset=utf-8");

PrintWriter out = response.getWriter();

try {

DiskFileItemFactory factory = new DiskFileItemFactory();

ServletFileUpload sevletFileUpload = new ServletFileUpload(factory);

// 设置允许用户上传文件大小,单位:字节,这里设为2m

sevletFileUpload.setSizeMax(2 * 1024 * 1024 * 100);

// 设置最多只允许在内存中存储的数据,单位:字节

factory.setSizeThreshold(4096);

// 设置一旦文件大小超过getSizeThreshold()的值时数据存放在硬盘的目录

factory.setRepository(new File("d:\\upload\\temp"));

// 开始读取上传信息

List fileItems = sevletFileUpload.parseRequest(request);

// 依次处理每个上传的文件

Iterator iter = fileItems.iterator();

// 正则匹配,过滤路径取文件名

String regExp = ".+\\\\(.+)$";

//上传的路径

String path="D:\\upload\\";

// 过滤掉的文件类型

String[] errorType = { ".exe", ".com", ".cgi", ".asp",".class" };

String[] accessType={".rar",".txt"};

Pattern p = Pattern.compile(regExp);

while (iter.hasNext()) {

FileItem item = (FileItem) iter.next();

// 忽略其他不是文件域的所有表单信息

if (!item.isFormField()) {


String name = item.getName();

long size = item.getSize();

double mSize=size/(1024);

if ((name == null || name.equals("")) && size == 0)

continue;

Matcher m = p.matcher(name);

boolean result = m.find();

if (result) {

for (int temp = 0; temp < errorType.length; temp++) {

if (m.group(1).endsWith(errorType[temp])) {

throw new IOException(name + ": 非法文件类型禁止上传");

}

}

// for (int temp = 0; temp < accessType.length; temp++) {
//
// if (!m.group(1).endsWith(accessType[temp])) {
//
// throw new IOException(name + ": 非法文件类型禁止上传");
//
// }
//
// }

try {

// 保存上传的文件到指定的目录

item.write(new File(path+ m.group(1)));

// 在下文中上传文件至数据库时,将对这里改写开始



String str=m.group(1);

int start=str.lastIndexOf(".")+1;

int end=str.length();

String fileName=str.substring(0,start-1);

String type=m.group(1).substring(start, end);

Date date=new Date();

Calendar calendar=new GregorianCalendar();

String printDate=calendar.get(calendar.YEAR)+"年";

printDate+=(calendar.get(calendar.MONTH)+1)+"月";

printDate+=calendar.get(calendar.DAY_OF_MONTH)+"日";

SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy年MM月dd日");

//simpleDateFormat.format(date).toString();

out.print("文件上传成功:<br>");

out.print("文件名:"+name + "  " +"<br>");

out.print("上传后的文件:"+path+m.group(1)+"<br>");

out.print("文件大小:"+ mSize + "K<br>");

out.print("文件格式:"+type+"<br>");

out.print("文件名:"+fileName+"<br>");

out.print("上传时间: "+printDate+"<br>");

out.print("simpleDateFormat:"+simpleDateFormat.format(date).toString());

// 在下文中上传文件至数据库时,将对这里改写结束

} catch (Exception e) {

out.println(e);

}
} else {

throw new IOException("上传失败!");

}

}

}

} catch (IOException e) {

out.println(e);

} catch (FileUploadException e) {

out.println(e);

}

}

}


demo.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>DEMO</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>
upload
<form action="upload" method="post" enctype="multipart/form-data" name="form1">
<input type="file" name="file" />
<input type="submit" name="submit" value="上传" />
</form>
<br>
</body>
</html>



<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.4" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<servlet>
<servlet-name>upload</servlet-name>
<servlet-class>Upload</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>upload</servlet-name>
<url-pattern>/upload</url-pattern>
</servlet-mapping>
</web-app>

需要的包有:commons-io commons-fileupload
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值