java多文件上传

来源:互联网 发布:轰炸手机号软件下载 编辑:程序博客网 时间:2024/05/16 11:07

自己遇到这样的东西 先大概写了一个模型

用的swfupload+struts

或者单独的 swfupload +serverlet



具体的代码 请见:java多文件上传代码

 文件在程序中的位置具体如下:

点击查看

必须的包:lib里面的包都是必须的。

索要引用的js 有 jquery和 handlers(主要就是控制文件上传的一些js)和swfupload 和一个必要的flash swupload 这些 官网都有地址是:swfupload。里面也有详细的讲解。



先说  struts的这一种,现在用struts的比较多:

首先建立 Uploadfile文件

package com;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.sql.Timestamp;import javax.servlet.ServletContext;import org.apache.commons.io.FileUtils;import org.apache.commons.lang3.StringUtils;import org.apache.struts2.ServletActionContext;import com.opensymphony.xwork2.ActionSupport;public class UploadFile extends ActionSupport {private String message ;public String getMessage() {return message;}public void setMessage(String message) {this.message = message;}private File files;private String filesFileName;private String filesContentType ;public File getFiles() {return files;}public void setFiles(File files) {this.files = files;}public String getFilesFileName() {return filesFileName;}public void setFilesFileName(String filesFileName) {this.filesFileName = filesFileName;}public String getFilesContentType() {return filesContentType;}public void setFilesContentType(String filesContentType) {this.filesContentType = filesContentType;} public String getInfo(){setMessage("linlin");return SUCCESS;}/**** * swf上传. 文件名字没有改变 */ public String swfUpload1() throws Exception {         // 实现上传        InputStream is = new FileInputStream(files);        /**获取路径**/        String root =ServletActionContext.getServletContext().getRealPath("");        /**分隔符**/String separator = java.io.File.separator;/**存储路径**/String path = root+separator+"upload" +separator+"file"+separator;System.out.println("---上传文件地址---"+path);//获取时间戳long time = System.currentTimeMillis();        File deskFile = new File(root, this.getFilesFileName());        System.out.println("--文件名字--"+this.getFilesFileName());        OutputStream os = new FileOutputStream(deskFile);        byte[] bytefer = new byte[1024];        int length = 0;        while ((length = is.read(bytefer)) != -1) {            os.write(bytefer, 0, length);        }        os.close();        is.close();        return "success";    } /**** * 使用FileUtils.copyFile的上传 * @return */public String loadFile(){/**当前时间戳**/Timestamp currentTime = new Timestamp(System.currentTimeMillis());ServletContext servletContext = ServletActionContext.getServletContext(); /**获取路径**/    String dataDir = servletContext.getRealPath(""); long time = System.currentTimeMillis();/**分隔符**/String separator = java.io.File.separator;/**判断上传文件是否为空**/if(null == files){/**若文件为空 则 报错**/return "文件为空!";}else{// 判断数据是否正确// 文件后缀名int index = StringUtils.lastIndexOf(filesFileName, '.');if (index == -1) {return "文件类型错误!";}/**获取文件后缀名**/String extFileName = StringUtils.substring(filesFileName, index + 1);/**定义上传位置**/String path = dataDir+separator+"upload" +separator+"file"+separator;System.out.println("---文件上传位置---"+path);/**使用当前时间戳,避免文件重复被覆盖**/String name = time+"";String filename = path + name + "." + extFileName.toLowerCase();;System.out.println("---文件名称---"+name);File destFile = new File(filename);try {/**上传文件 用FileUtils**/FileUtils.copyFile(files, destFile);} catch (IOException e) {e.printStackTrace();return "附件上传失败!";}}         return SUCCESS;} /****  *    * 使用IO 流  * @return  * @throws IOException  */public String  swfUpload() throws IOException{if(null == files){/**若文件为空 则 报错**/return "文件为空!";}else{// 判断数据是否正确// 文件后缀名int index = StringUtils.lastIndexOf(filesFileName, '.');if (index == -1) {return "文件类型错误!";}/**获取文件后缀名**/String extFileName = StringUtils.substring(filesFileName, index + 1); /**分隔符**/String separator = java.io.File.separator;/**定义上传位置**/        String root =ServletActionContext.getServletContext().getRealPath("");String path = root+separator+"upload" +separator+"file"+separator;System.out.println("---文件上传位置---"+path);/**使用当前时间戳,避免文件重复被覆盖**/long time = System.currentTimeMillis();String name = time+"";String filename = path + name + "." + extFileName.toLowerCase();        File deskFile = new File(filename);System.out.println("---文件名称---"+name);InputStream is = new FileInputStream(files);        OutputStream os = new FileOutputStream(deskFile);        byte[] bytefer = new byte[1024];        int length = 0;        while ((length = is.read(bytefer)) != -1) {            os.write(bytefer, 0, length);        }        os.close();        is.close();        return "success";} }}

struts.xml的配置:

<package name="uploadfile" extends="struts-default" namespace="/"><action name="getinfo" class="com.UploadFile" method="getInfo"><result name="success">/upload.jsp</result></action><action name="uploadfile" class="com.UploadFile" method="loadFile"><result name="success">/upload.jsp</result></action><action name="swfuploadfile" class="com.UploadFile" method="swfUpload"><result name="success">/upload.jsp</result></action><!--删除附件--><action name="deletefile" class="com.deletFile" method="delFile"><result name="success">/upload.jsp</result></action></package>

上传页面

index.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"><!--<link rel="stylesheet" type="text/css" href="styles.css">-->  </head>  <script type="text/javascript" src="swfupload/swfupload.js"></script>  <script type="text/javascript" src="swfupload/handlers.js"></script>  <script type="text/javascript" src="js/jquery-1.4.2.min.js"></script>  <body style="font-size: 12px;">   <script type="text/javascript">var swfu;window.onload = function () {swfu = new SWFUpload({upload_url: "swfuploadfile.action" //上传文件需要请求的url,// File Upload Settingsfile_size_limit : "50 MB",// 1000MBfile_types : "*.*",//设置可上传的类型file_types_description : "所有文件",file_upload_limit : "10",                file_post_name: "files",//相当于页面的name属性file_queue_error_handler : fileQueueError,//选择文件后出错file_dialog_complete_handler : fileDialogComplete,//选择好文件后提交file_queued_handler : fileQueued,upload_progress_handler : uploadProgress,upload_error_handler : uploadError,upload_success_handler : uploadSuccess,upload_complete_handler : uploadComplete,// Button Settingsbutton_image_url : "images/SmallSpyGlassWithTransperancy_17x18.png",button_placeholder_id : "spanButtonPlaceholder",button_width: 100,button_height: 18,button_text : '<span class="button">添加附件</span>',button_text_style : '.button { font-family: Helvetica, Arial, sans-serif; font-size: 12pt; } .buttonSmall { font-size: 10pt; }',button_text_top_padding: 0,button_text_left_padding: 18,button_window_mode: SWFUpload.WINDOW_MODE.TRANSPARENT,button_cursor: SWFUpload.CURSOR.HAND,// Flash Settingsflash_url : "swfupload/swfupload.swf",custom_settings : {upload_target : "divFileProgressContainer"},// Debug Settingsdebug: false  //是否显示调试窗口});};function startUploadFile(){swfu.startUpload();}</script><!--  --><span id="spanButtonPlaceholder"></span>  <div id="divFileProgressContainer" style="width:200;display:none;"></div><div id="thumbnails"><table id="infoTable" border="0" width="50%" style="border: solid 1px #7FAAFF; background-color: #C5D9FF; padding: 2px;margin-top:8px;"></table></div>  </body></html>

这个效果是这样的选择一个文件自动上传一个文件:



然后 可以一次性选择完进行上传:

swfUpload.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"><!--<link rel="stylesheet" type="text/css" href="styles.css">-->  </head>  <script type="text/javascript" src="swfupload/swfupload.js"></script>  <script type="text/javascript" src="swfupload/handlers.js"></script>  <script type="text/javascript" src="js/jquery-1.4.2.min.js"></script>  <body style="font-size: 12px;">   <script type="text/javascript">var swfu;var index = 1;window.onload = function () {swfu = new SWFUpload({upload_url: "swfuploadfile.action",//要请求的action名字// File Upload Settingsfile_size_limit : "50 MB",// 1000MBfile_types : "*.*",//设置可上传的类型file_types_description : "所有文件",file_upload_limit : "10", //上传文件的名称                file_post_name: "files",//相当于页面的name属性                file_queue_error_handler : fileQueueError,//选择文件后出错file_dialog_complete_handler : fileDialogComplete,//用于处理选择文件后出发的事件file_queued_handler : fileQueued,upload_progress_handler : uploadProgress,upload_error_handler : uploadError,//上传文件失败触发的事件upload_success_handler : uploadSuccess,//上传文件成功触发的事件upload_complete_handler : uploadComplete,//用于处理文件上传结束之后的事件// Button Settingsbutton_image_url : "images/SmallSpyGlassWithTransperancy_17x18.png",//指向button图片额的地址button_placeholder_id : "spanButtonPlaceholder",//button的iDbutton_width: 100,//button的宽度button_height: 18,//button的高度button_text : '<span class="button">添加附件</span>',//button里面的文字button_text_style : '.button { font-family: Helvetica, Arial, sans-serif; font-size: 12pt; } .buttonSmall { font-size: 10pt; }',button_text_top_padding: 0,button_text_left_padding: 18,button_window_mode: SWFUpload.WINDOW_MODE.TRANSPARENT,button_cursor: SWFUpload.CURSOR.HAND,// Flash Settingsflash_url : "swfupload/swfupload.swf",//flash的地址custom_settings : {upload_target : "divFileProgressContainer"},// Debug Settingsdebug: false  //是否显示调试窗口});};function uploadComplete(file){//continue to  upload next fileswfu.startUpload();  }function fileDialogComplete(numFilesSelected ,numFilesQueued,numFilesinQueue){var table = document.getElementById("filesTable");table.style.display="block";}function fileQueued(file){var table = document.getElementById("filesTable");var row = table.insertRow();var col1= row.insertCell();var col2= row.insertCell();var col3= row.insertCell();var col4= row.insertCell();row.id = file.id;col4.id=index;col1.innerHTML = file.name; col2.innerHTML = file.size;col3.innerHTML = showStatus(file.filestatus);col4.innerHTML = "<input type='button' value = '删除'onclick='deleteRow("+index+")'/>";index++;}function showStatus(status){var word ;switch(status){case  SWFUpload.FILE_STATUS.QUEUED:  word="queued";  break;case  SWFUpload.FILE_STATUS.ERROR:  word="ERROR";  break;case  SWFUpload.FILE_STATUS.COMPLETE:  word="COMPLETE";  break;}return word;}function uploadSuccess(file){var row = document.getElementById(file.id);row.cells[2].innerHTML=showStatus(file.filestatus);}function uploadError(file){var row = document.getElementById(file.id);row.cells[2].innerHTML=showStatus(file.filestatus);}function startUploadFile(){swfu.startUpload();}function deleteRow(obj) {  var x=document.getElementById(obj);   x.parentNode.parentNode.removeChild(x.parentNode);}  </script><!--  --><span id="spanButtonPlaceholder"></span><div ><table id="filesTable" border="0" width="50%" style="display: none"><tr><td>name</td><td>size</td><td>status</td><td>del</td></tr></table><div><button onclick="startUploadFile()">上传</button>  </body></html>
效果是这样的:



然后点击上传 一次性上传这些文件,其实 看上去是一次性上传的,其实是一个一个激动上传的,等于是系统自动调用了后台三次。


删除以后再说,



原创粉丝点击