转自: https://blessht.iteye.com/blog/1405057

最近自己在做一个小系统玩的时候涉及到了文件的上传,于是在网上找到Java上传文件的方案,最后确定使用common-fileupload实现上传操作。

  • 需求说明

用户添加页面有一个“上传”按钮,点击按钮弹出上传界面,上传完成后关闭上传界面。

  • 所需Jar包

commons.fileupload-1.2.0.jar、commons.logging-1.1.1.jar、commons.beanutils-1.8.0.jar、commons.collections-3.2.0.jar、commons.io-1.4.0.jar、commons.lang-2.1.0.jar

  • 实现效果

  • 代码实现
首先编写核心代码,Javascript打开上传页面,并且从上传页获取返回参数,最后数据返回给回调函数callback:
 
 <%@ 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" />
<title>定义input type="file" 的样式</title>
<style type="text/css">
body {
font-size: 14px;
} input {
vertical-align: middle;
margin: 0;
padding: 0
} .file-box {
position: relative;
width: 340px
} .txt {
height: 22px;
border: 1px solid #cdcdcd;
width: 180px;
} .btn {
background-color: #FFF;
border: 1px solid #CDCDCD;
height: 24px;
width: 70px;
} .file {
position: absolute;
top: 0;
right: 80px;
height: 24px;
filter: alpha(opacity : 0);
opacity: 0;
width: 260px
}
</style>
<script>
/**
* 跳转到上传页
* functionId:功能ID
* fileType:文件类型
* maxSize:文件容量上限
* callback:回调函数,返回三个参数:文件真名、文件存放名和文件大小
用户添加页面相关代码,点击“上传”按钮时调用上面的核心js代码,并且获取返回值
*/
function openUpload(functionId, fileType, maxSize, callback) {
var url = root + "/CommonController.jhtml?method=goFileUpload&";
if (functionId != null) {
url = url + "functionId=" + functionId + "&";
}
if (fileType != null) {
url = url + "fileType=" + fileType + "&";
}
if (maxSize != null) {
url = url + "maxSize=" + maxSize;
}
var win = window.showModalDialog(url, "",
"dialogWidth:300px;dialogHeight:150px;scroll:no;status:no");
if (win != null) {
var arrWin = win.split(",");
callback(arrWin[0], arrWin[1], arrWin[2]);
}
}
<script>
....... function openUpload_(){
openUpload(null,'JPG,GIF,JPEG,PNG','5',callback);
} /**
* 回调函数,获取上传文件信息
* realName真实文件名
* saveName文件保存名
* maxSize文件实际大小
*/
function callback(realName,saveName,maxSize){
$("#photo_").val(saveName);
//回调后其它操作
}
</script>
</script>
</head>
<body> <div class="file-box">
<tr>
<td>头像:</td>
<td><input type="hidden" name="photo" id="photo_"></input> <input
type="button" onclick="openUpload_();" value="上传" /></td>
</tr>
</div>
</body>
</html>

文件上传的JSP代码,需要注意的是在head标签内添加<base target="_self">以防止页面跳转时弹出新窗口,用户选择指定文件,点击上传时就提交表单访问指定后台代码

     <%@ include file="/WEB-INF/jsp/header.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=ISO-8859-1">
<meta http-equiv="pragma" content="no-cache" />
<base target="_self">
<title>文件上传</title>
</head>
<body>
<h5>文件上传</h5><hr/>
<form id="file_upload_id" name="file_upload_name" action="<%=root%>/CommonController.jhtml?method=doFileUpload" method="post" enctype="multipart/form-data">
<input type="hidden" name="functionId" value="${functionId}"/>
<input type="hidden" name="fileType" value="${fileType}"/>
<input type="hidden" name="maxSize" value="${maxSize}"/>
<div><input type="file" name="file_upload"/></div>
<c:if test="${maxSize!=null}">
<div style="font: 12">文件最大不能超过${maxSize}MB</div>
</c:if>
<c:if test="${fileType!=null}">
<div style="font: 12">文件格式必须是:${fileType}</div>
</c:if>
<div><input type="submit" value="上传"/></div>
</form>
</body>
</html>

CommonController目前有两个方法,一个是跳转到上传页面的方法,一个是执行上传操作的方法doFileUpload,上传方法运行的大概逻辑是:首先获取页面的请求参数,fileType用于限制上传文件格式,

maxSize用于限制上传文件最大值,随后创建上传目录上传即可。

     public class CommonController extends BaseController {
Log log = LogFactory.getLog(CommonController.class); Properties fileUploadPro = null;
public CommonController(){
fileUploadPro = PropertiesUtil.getPropertiesByClass("fileupload.properties");
} @Override
public ModeAndView init(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException { return null;
} /**
* 跳转到文件上传页
* @param request
* @param response
* @return
* @throws ServletException
* @throws IOException
*/
public ModeAndView goFileUpload(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String functionId = request.getParameter("functionId");
String fileType = request.getParameter("fileType");
String maxSize = request.getParameter("maxSize");
ModeAndView mav = new ModeAndView("/WEB-INF/jsp/common/fileUpload.jsp"); if(functionId!=null && !"".equals(functionId.trim())){
mav.addObject("functionId", functionId);
}
if(fileType!=null && !"".equals(fileType.trim())){
mav.addObject("fileType", fileType);
}
if(maxSize!=null && !"".equals(maxSize.trim())){
mav.addObject("maxSize", maxSize);
}
return mav;
} /**
* 上传文件
* @param request
* @param response
* @return
* @throws ServletException
* @throws IOException
*/
@SuppressWarnings("unchecked")
public ModeAndView doFileUpload(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
//获取并解析文件类型和支持最大值
String functionId = request.getParameter("functionId");
String fileType = request.getParameter("fileType");
String maxSize = request.getParameter("maxSize"); //临时目录名
String tempPath = fileUploadPro.getProperty("tempPath");
//真实目录名
String filePath = fileUploadPro.getProperty("filePath"); FileUtil.createFolder(tempPath);
FileUtil.createFolder(filePath); DiskFileItemFactory factory = new DiskFileItemFactory();
//最大缓存
factory.setSizeThreshold(5*1024);
//设置临时文件目录
factory.setRepository(new File(tempPath));
ServletFileUpload upload = new ServletFileUpload(factory);
if(maxSize!=null && !"".equals(maxSize.trim())){
//文件最大上限
upload.setSizeMax(Integer.valueOf(maxSize)*1024*1024);
} try {
//获取所有文件列表
List<FileItem> items = upload.parseRequest(request);
for (FileItem item : items) {
if(!item.isFormField()){
//文件名
String fileName = item.getName(); //检查文件后缀格式
String fileEnd = fileName.substring(fileName.lastIndexOf(".")+1).toLowerCase();
if(fileType!=null && !"".equals(fileType.trim())){
boolean isRealType = false;
String[] arrType = fileType.split(",");
for (String str : arrType) {
if(fileEnd.equals(str.toLowerCase())){
isRealType = true;
break;
}
}
if(!isRealType){
//提示错误信息:文件格式不正确
super.printJsMsgBack(response, "文件格式不正确!");
return null;
}
} //创建文件唯一名称
String uuid = UUID.randomUUID().toString();
//真实上传路径
StringBuffer sbRealPath = new StringBuffer();
sbRealPath.append(filePath).append(uuid).append(".").append(fileEnd);
//写入文件
File file = new File(sbRealPath.toString());
item.write(file);
//上传成功,向父窗体返回数据:真实文件名,虚拟文件名,文件大小
StringBuffer sb = new StringBuffer();
sb.append("window.returnValue='").append(fileName).append(",").append(uuid).append(".").append(fileEnd).append(",").append(file.length()).append("';");
sb.append("window.close();");
super.printJsMsg(response, sb.toString());
log.info("上传文件成功,JS信息:"+sb.toString());
}//end of if
}//end of for }catch (Exception e) {
//提示错误:比如文件大小
super.printJsMsgBack(response, "上传失败,文件大小不能超过"+maxSize+"M!");
log.error("上传文件异常!",e);
return null;
} return null;
}
}

至此一个文件上传即已实现,而且能够基本满足不同模块的上传通用性,我还留着个functionId参数用于以后针对不同模块上传文件到不同目录。

Java实现文件上传-按钮弹出上传页面的更多相关文章

  1. js实现点击按钮弹出上传文件的窗口

    转自:https://www.jb51.net/article/100916.htm 1.详细描述 在页面上设置一个“选择文件”按钮,点击该按钮,会弹出本地磁盘信息用于选择文件. 2.代码 ? 1 2 ...

  2. HTML-通过点击网页上的文字弹出QQ添加好友页面

    在网上参考了部分方法,综合了一下. 发现有2中方式: 第一种是不能直接弹出添加界面的,只能弹出网页,再通过网页中的添加好友才能添加: 弹出的网页是这样的(我是写成在新的网页中打开) 现在看实现的代码: ...

  3. ExtJs 4.2.1 点击按钮弹出表单的窗口

    初学ExtJs,做项目的时候想做一个这样的效果:点击按钮弹出对话框,之前一直是使用EasyUi来做的, EasyUi里有Dialog,用起来很方便,但是现在转移到ExtJs上后,发现没有Dialog这 ...

  4. Html : 点击按钮弹出输入框,再次点击进行隐藏

    上代码: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3 ...

  5. JavaScript实现点击按钮弹出输入框,点确定后添加li组件到ul组件里

    JavaScript实现点击按钮弹出输入框,点确定后添加li组件到ul组件里 <!doctype html> <html manifest="lab4.manifest&q ...

  6. ExtJS003单击按钮弹出window

    html部分 <input type="button" id="btn" name="name" value="点击&quo ...

  7. Menubutton按钮弹出菜单

    #按钮弹出菜单 from tkinter import * root =Tk() def callback(): print('我被调用了') m = Menubutton(root,text = ' ...

  8. xtraTabbedMdiManager的标题上右鍵弹出关闭窗体菜单

    实现一个增值功能, 在xtraTabbedMdiManager组件TabPage标题上右鍵弹出关闭当前窗体的菜单. C# Code: private void xtraTabbedMdiManager ...

  9. 请写出一段JavaScript代码,要求页面有一个按钮,点击按钮弹出确认框。程序可以判断出用

    请写出一段JavaScript代码,要求页面有一个按钮,点击按钮弹出确认框.程序可以判断出用 户点击的是“确认”还是“取消”. 解答: <HTML> <HEAD> <TI ...

随机推荐

  1. MySQL_DML操作

    DML(Data Manipulation Laguage)指对数据库数据的增(Create)删(Delete)改(Update)操作 1.增加操作 (1)先创建一个表,如图所示: 语法:Insert ...

  2. EcShop开发手册

    Ecshop文件结构 ecshop文件架构说明 ECShop 结构图及各文件相应功能介绍 ECShop upload 的目录 ┣ activity.php 活动列表 ┣ affiche.php 广告处 ...

  3. 【Python】学习笔记十四:循环进阶

    range() 在Python中,for循环后的in跟随一个序列的话,循环每次使用的序列元素,而不是序列的下标. 我们继续开发range的功能,以实现下标对循环的控制: s = 'abcdefghj' ...

  4. XAMPP 1.8.2-2 Apache Web Server won't start, always stops immediately

    sudo apachectl stop apachectl是Apache超文本传输协议服务器的前端程序. 其设计意图是帮助管理员控制Apachehttpd后台的功能. MacOS中安装完Apache之 ...

  5. SpringBoot,用200行代码完成一个一二级分布式缓存

    缓存系统的用来代替直接访问数据库,用来提升系统性能,减小数据库复杂.早期缓存跟系统在一个虚拟机里,这样内存访问,速度最快. 后来应用系统水平扩展,缓存作为一个独立系统存在,如redis,但是每次从缓存 ...

  6. ClientScriptManager.RegisterClientScriptBlock Method 无效

    ClientScriptManager.RegisterClientScriptBlock Method 这个方法不能在Render方法里面使用,但是可以在PreRender中使用 最好是放到OnLo ...

  7. virt-manager 使用 shh 远程访问配置方法

    1.下载安装 Xming+Xshell  或者 Xming+putty,启动Xming服务 Xming下载地址 2.XMing的配置:打开XLaunch,记住Display Number,现在这里是0 ...

  8. Linux_Comand - Check disk space

    df -h du -sh Delete folder older than 30 days find /path -name "test-*" -type d -mtime +30 ...

  9. 2017-03-04 idea破解

    https://blog.csdn.net/qq_27686779/article/details/78870816 防止原址被删除,备份下,亲测可用 http://idea.java.sx/ 简单快 ...

  10. 一、Robotframework安装步骤

    1.安装python并验证安装成功 a.安装python-2.7.14.amd64------默认路径安装即可 b.添加环境变量path:C:\Python27; C:\Python27\Script ...