SWFUpload文件上传服务器端采用Java接收
官方的版本中只有php的版本,从网上找了其他人写的内容,自己实现了一个servlet的版本,
但是又出现另一个问题,如何向后台传递参数的问题,现在整理出来,以备忘。
问题:
1、编码问题,做的示例用的gb18030,所以后台很多的转码问题,采用UTF-8,能好一些,
2、传递中文问题,最好还是前台进行encoding,(encodeURI),后台进行解析取出来吧--未测试
上代码:
一、前台页面index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%> <% 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>文件上传swfupload使用</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"> --> <link href="<%=basePath%>css/default.css" rel="stylesheet" type="text/css" /> <script type="text/javascript" src="<%=basePath%>swfupload/swfupload.js"></script> <script type="text/javascript" src="<%=basePath%>swfupload/swfupload.queue.js"></script> <script type="text/javascript" src="<%=basePath%>js/fileprogress.js"></script> <script type="text/javascript" src="<%=basePath%>js/handlers.js"></script> <script type="text/javascript"> var swfu; SWFUpload.onload = function () { var settings = { flash_url : "<%=basePath%>swfupload/swfupload.swf", flash9_url : "<%=basePath%>swfupload/swfupload_fp9.swf", upload_url: "<%=basePath%>upload", post_params: { "hello" : "Here I Am", "name" : "张三" }, file_size_limit : "100 MB", file_types : "*.*", file_types_description : "All Files", file_upload_limit : 100, file_queue_limit : 0, custom_settings : { progressTarget : "fsUploadProgress", cancelButtonId : "btnCancel" }, debug: true, use_query_string : true,//要传递参数,必须配置,可以从后台取到参数,应该还有其他方式,如post方式,未了解 // Button Settings button_image_url : "<%=basePath%>images/TestImageNoText_65x29.png", button_placeholder_id : "spanButtonPlaceholder", button_width: 61, button_height: 22, button_text: '浏览', button_text_style: ".spanButtonPlaceholder { font-size: 12; }", button_text_left_padding: 12, button_text_top_padding: 3, // The event handler functions are defined in handlers.js //swfupload_preload_handler : preLoad, //swfupload_load_failed_handler : loadFailed, file_queued_handler : fileQueued, file_queue_error_handler : fileQueueError, file_dialog_complete_handler : fileDialogComplete, upload_start_handler : uploadStart, upload_progress_handler : uploadProgress, upload_error_handler : uploadError, upload_success_handler : uploadSuccess, upload_complete_handler : uploadComplete, queue_complete_handler : queueComplete // Queue plugin event }; swfu = new SWFUpload(settings); } </script> </head> <body> <div class="fieldset flash" id="fsUploadProgress"> <span class="legend">文件列表:</span> </div> <div id="divStatus">上传了0个文件</div> <div class="flash" id="fsUploadProgress"> </div> <div style="padding-left: 5px;"> <span id="spanButtonPlaceholder"></span> <input id="btnCancel" type="button" value="取消" onclick="cancelQueue(upload);" disabled="disabled" style="margin-left: 2px; height: 22px; font-size: 8pt;" /> </div> <!-- 上传文件列表 --> <div class="fileList" id="fileList"> </div> </body> </html>
二、前台接收后台返回数据的位置 --handler.js-只需要找到该位置,进行修改就可以了
function uploadSuccess(file, serverData) { try { var progress = new FileProgress(file, this.customSettings.progressTarget); progress.setComplete(); progress.setStatus("上传完成."); progress.toggleCancel(false); alert(serverData); //后台传递回来的内容 var serdata = document.getElementById("fileList"); serdata.innerHTML = serverData; } catch (ex) { this.debug(ex); } }
三、后台servlet-Upload.java,下边只列出了用到的doPost()方法,其他内容都没有变化
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //接收参数 String hello = request.getParameter("hello"); String name = request.getParameter("name"); name = new String(name.getBytes("ISO-8859-1"),"UTF-8");//字符编码问题,可以通过前台encoding后台再解析 System.out.println("接收参数,hello="+hello+",name="+name); String path1 = request.getRequestURI()+"/files"; System.out.println("____________request.getRequestURI():"+path1); String path2 = request.getSession().getServletContext().getRealPath("/"); System.out.println("_________path2:"+path2); List<FileEntity> fileList; fileList = (List)request.getAttribute("fileList"); if(fileList==null) fileList = new ArrayList<FileEntity>(); //接收上传文件 String uploadSign = request.getParameter("upload"); String rootPath = request.getParameter("rootPath"); String path = request.getParameter("path"); if(rootPath == null) rootPath = ""; rootPath = rootPath.trim(); if(rootPath.equals("")){ //rootPath = application.getRealPath("/swfupload/files");//自由修改处二:指定服务器固定文件 rootPath = path2+"/files"; } if(path == null) { path = rootPath; }else{ path = new String(Base64.decodeBase64(path.getBytes())); } System.out.println(path+"...path.getBytes():"+path.getBytes()); uploadSign = "1"; //上传操作 if(null != uploadSign && !"".equals(uploadSign)){ FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); //upload.setHeaderEncoding("UTF-8"); try{ List items = upload.parseRequest(request); if(null != items){ Iterator itr = items.iterator(); int i = 0; while(itr.hasNext()){ FileItem item = (FileItem)itr.next(); FileEntity file = new FileEntity();//_____________________ if(item.isFormField()){ continue; }else{ //自由修改处三:可修改上传后的文件命名方式 SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddkkmmss");//以当前精确到秒的日期为上传的文件的文件名 SimpleDateFormat sdd=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String type = item.getName().split("\\.")[1];//获取文件类型 System.out.println("——————————————————文件名称:"+item.getName()); System.out.println("从GBK转到UTF-8输出:"+new String(item.getName().getBytes("GBK"),"UTF-8")); File savedFile = new File(path,sdf.format(new Date())+"."+type); //把文件放到列表中,在前台显示 System.out.println("__________________服务器上对应的文件名称:"+sdf.format(new Date())+"."+type); System.out.println("__________________完整路径:"+path1+"/"+sdf.format(new Date())+"."+type); file.setId(sdf.format(new Date())); file.setDate(sdd.format(new Date())); file.setFilename(item.getName()); file.setFilepath(path1+"/"+sdf.format(new Date())+"."+type); file.setFilesize(item.getSize()+""); file.setFiletype(type); file.setMark("0"); fileList.add(file); item.write(savedFile); } } } }catch(Exception e){ e.printStackTrace(); } } response.setContentType("text/html"); response.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); if(fileList!=null){ for(int i=0;i<fileList.size();i++){ FileEntity file = (FileEntity)fileList.get(i); //out.println("文件:"+ new String(file.getFilename().getBytes("GBK"),"UTF-8")+",文件路径:"+file.getFilepath()); out.println("文件:"+ new String(file.getFilename().getBytes("GBK"),"UTF-8")+",上传成功!"); } } }
四、自定义的一个文件类FileEntity.java,测试时全部用的String类型
package com.swfupload.entity; public class FileEntity { private String id; private String belong; private String filename; private String filepath; private String filetype; private String filesize; private String date; private String mark; public FileEntity(){} public String getId() { return id; } public void setId(String id) { this.id = id; } public String getBelong() { return belong; } public void setBelong(String belong) { this.belong = belong; } public String getFilename() { return filename; } public void setFilename(String filename) { this.filename = filename; } public String getFilepath() { return filepath; } public void setFilepath(String filepath) { this.filepath = filepath; } public String getFiletype() { return filetype; } public void setFiletype(String filetype) { this.filetype = filetype; } public String getFilesize() { return filesize; } public void setFilesize(String filesize) { this.filesize = filesize; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } public String getMark() { return mark; } public void setMark(String mark) { this.mark = mark; } public static void main(String[] agrs){ String str=""; System.out.println(str); } }
本文由用户 jopen 自行上传分享,仅供网友学习交流。所有权归原作者,若您的权利被侵害,请联系管理员。
转载本站原创文章,请注明出处,并保留原始链接、图片水印。
本站是一个以用户分享为主的开源技术平台,欢迎各类分享!