首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 其他教程 > 开源软件 >

SWFUploadv.2.2.0上传-java后台老板代码

2012-06-26 
SWFUploadv.2.2.0上传-java后台代码后台代码用servlet,这样不依赖框架什么情况,都可以用。?web.xml添加??!

SWFUploadv.2.2.0上传-java后台代码

后台代码用servlet,这样不依赖框架什么情况,都可以用。

?

web.xml添加

?

?

<!-- swfupload 上传 begin --><servlet><servlet-name>SWFUploader</servlet-name><servlet-class>sunfish.upload.SWFUploadServlet</servlet-class><load-on-startup>0</load-on-startup></servlet><servlet-mapping><servlet-name>SWFUploader</servlet-name><url-pattern>/upload/SWFUploader</url-pattern></servlet-mapping><!-- swfupload 上传 end -->

?

java代码如下:

?

?

package sunfish.upload;import java.io.File;import java.io.IOException;import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.UUID;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import net.sf.json.JSONObject;import org.apache.commons.fileupload.FileItem;import org.apache.commons.fileupload.FileItemFactory;import org.apache.commons.fileupload.disk.DiskFileItemFactory;import org.apache.commons.fileupload.servlet.ServletFileUpload;import org.apache.commons.lang.StringUtils;public class SWFUploadServlet extends HttpServlet {public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {String relativePath = request.getParameter("relativePath");if (StringUtils.isEmpty(relativePath))relativePath = "upload";// 设定上传文件路径String currentPath = relativePath + "/";// 获得web应用的上传路径String currentDirPath = getServletContext().getRealPath(currentPath);System.out.println("currentDirPath=" + currentDirPath);// 判断文件夹是否存在,不存在则创建File dirTest = new File(currentDirPath);if (!dirTest.exists()) {dirTest.mkdirs();}boolean status = false;String msg = "";// 使用Apache Common组件中的fileupload进行文件上传FileItemFactory factory = new DiskFileItemFactory();ServletFileUpload upload = new ServletFileUpload(factory);String newFileName = null;try {String fileName = null;FileItem uplFile = null;List<FileItem> itemList = upload.parseRequest(request);// Iterator iter = items.iterator();System.out.println("enctype=multipart/form-data 参数解析  begin----------");for (FileItem item : itemList) {// FileItem item = (FileItem) iter.next();if (item.isFormField()) {// 这里Filename和下面的Filedata都是swflupoad设置的默认设置,够无聊的话你可以去修改// 另外不同的浏览器传递的Filename可能不同,或全路径,或只是文件名称if (item.getFieldName().equals("Filename")) {fileName = item.getString();}} else {if (item.getFieldName().equals("Filedata")) {uplFile = (FileItem) item;}}System.out.println(item.getFieldName() + "=" + item);}// end of forSystem.out.println("enctype=multipart/form-data 参数解析  end----------");// CEKditor中file域的name值是upload// 获取文件名(无扩展名)newFileName = createNewFileName(fileName);File pathToSave = new File(currentDirPath, newFileName);// 如果文件名相同,则重写且名字int counter = 1;while (pathToSave.exists()) {if (counter == 10) {throw new IOException("名称重复:" + counter);}newFileName = createNewFileName(fileName);pathToSave = new File(currentDirPath, newFileName);counter++;}uplFile.write(pathToSave);status = true;} catch (Exception ex) {ex.printStackTrace();throw new IOException(ex.getMessage());}// 以Jsong格式为输出信息// response.setContentType("text/html; charset=UTF-8");response.setContentType("application/json;charset=UTF-8");response.setHeader("Pragma", "No-cache");response.setHeader("Cache-Control", "no-cache");response.setDateHeader("Expires", 0);Map<String, String> data = new HashMap<String, String>();data.put("newFileName", newFileName);data.put("relativePath", relativePath);String result = JSONObject.fromObject(data).toString();System.out.println("json:\n" + result);response.getWriter().write(result);response.getWriter().flush();response.getWriter().close();}public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {doPost(request, response);}private static String createNewFileName(String oldFileName) {String ext = getExtension(oldFileName);// 获取文件扩展名String newName = UUID.randomUUID().toString() + "." + ext;return newName;}/** * 获取扩展名的方法 */private static String getExtension(String fileName) {return fileName.substring(fileName.lastIndexOf(".") + 1);}/** * Servlet初始化方法 */public void init() throws ServletException {}}

?

对于上面返回的json数据,你可以在如下handlers.js中的uploadSuccess(file, serverData)?方法里面获取:

?

?

function uploadSuccess(file, serverData) {try {var progress = new FileProgress(file, this.customSettings.progressTarget);progress.setComplete();progress.setStatus("上传成功");serverData=eval('('+serverData+')');  //string->jsonvar relativePath=serverData.relativePath;var newFileName=serverData.newFileName;alert("serverData.relativePath="+serverData.relativePath);alert("serverData="+serverData);//alert(serverData+"上传成功"+file.name);progress.toggleCancel(true);//不隐藏删除按钮} catch (ex) {this.debug(ex);}}
?

?

?

前台页面,只需要修改一些简单的地方就可以了,这里主要修改了upload_url,主要代码如下:

?

?

window.onload = function() {var settings = {flash_url : "<%=path%>/js/swfupload/swfupload.swf",upload_url: "<%=path%>/upload/SWFUploader?relativePath=upload/attachement",post_params: {"SESSID" : "<%=session.getId()%>"}, // 附加参数,版本2新功能   file_size_limit : "100 MB",//file_types : "*.*",//file_types : "*.txt;*.docx;*.doc,*.jpeg;*.png;*.jpg;*.gif",file_types : "*.txt;*.docx;*.doc,*.jpeg;*.png;*.jpg;*.gif;*.doc;*.ppt;*.xls;*.pps;*.docx;*.pptx;*.xlsx;*.rar;*.zip;*.swf;*.zip;*.zip;*.zip;*.zip;",file_types_description : "All Files", file_upload_limit : 2,file_queue_limit : 0,custom_settings : {progressTarget : "fsUploadProgress",cancelButtonId : "btnCancel"},debug: false,// Button settingsbutton_image_url: "<%=path%>/images/TestImageNoText_65x29.png",button_width: "65",button_height: "29",button_placeholder_id: "spanButtonPlaceHolder",button_text: '<span class="theFont">Hello</span>',button_text_style: ".theFont { font-size: 16; }",button_text_left_padding: 12,button_text_top_padding: 3,// The event handler functions are defined in handlers.jsfile_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>
?

完整的前台页面代码,可以到这里去下载:http://demo.swfupload.org/v220/simpledemo/index.php

?

?

参考:

http://demo.swfupload.org/v220/index.htm

http://www.swfupload.org/

http://demo.swfupload.org/Documentation/

?

?

%%%%

热点排行