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 for
			System.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->json
		var 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 settings

				button_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.js

				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>

 

完整的前臺頁面代碼,可以到這裏去下載:http://demo.swfupload.org/v220/simpledemo/index.php

 

 

參考:

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

http://www.swfupload.org/

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

 

 附件中有代碼:部署到tomcat中後,訪問http://localhost:8080/swfupload_demo/

附件

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章