JSP 파일 업로드 플러그 인 uploadify 사용

5809 단어 jsp/servlet
옆집 왕 씨http://wallimn.iteye.com/blog/1663299의 블 로그 에서 이 플러그 인 을 사용 하 는 글 을 보고 손 이 근질근질 하고 홈 페이지 에 가서 예 를 들 어 놀 았 는데 최신 판 API 가 변 할 줄 은 몰 랐 다.
자원 다운로드 주소PS: 자원 에 올 린 JS 가 제대로 쓰 이지 않 았 습 니 다. 여기 서 수정 되 었 습 니 다.
아니면 써 서 같이 공부 해 볼 까?
http://www.uploadify.com   홈 페이지
세 개의 파일 이 필요 합 니 다. jquery. uploadify. js, uploadify. css, uploadify. swf.이번 실험 은 my eclipse 8.5 에 배치 되 어 있 으 며, 도입 해 야 할 JAR 에는 3 개의 comons. jar 패키지 가 있 습 니 다. io, logging, fileupload.tomcat 의 lib 디 렉 터 리 에서 찾 을 수 있 습 니 다.
index. jsp 파일 은 다음 과 같 습 니 다.





  
    
    
    My JSP 'index.jsp' starting page
    



	
		
	$(document).ready(
			function() {        
				$("#uploadify").uploadify( {//     
				'swf'      : 'uploadify/uploadify.swf',
				'auto'     : false,//true     
				'uploader' : 'servlet/Upload',
				'multi' : true,
				'buttonText' : '  ',
				'simUploadLimit' : 8
			});

		});	

  
  
  
		



其中变化较大的是上传文件的函数,为upload()。

具体的参数可看jquery.uploadify.js,里面有详细的API说明

注意有三个属性是必须在初始化的时候赋值的,API那也有说明。

JSP使用文件上传插件uploadify_第1张图片

具体参数可参考

JSP使用文件上传插件uploadify_第2张图片


API的说明很详细。

接下来是SERVLET的。

package com.zcb.servlet;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
/**
 * 
 * @author zhengchubin
 *
 */
@SuppressWarnings("serial")
public class Upload extends HttpServlet {
    @SuppressWarnings("unchecked")
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String savePath = this.getServletConfig().getServletContext()
                .getRealPath("");
        savePath = savePath + "/uploads/";
        File f1 = new File(savePath);
        System.out.println(savePath);
        if (!f1.exists()) {
            f1.mkdirs();
        }
        DiskFileItemFactory fac = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(fac);
        upload.setHeaderEncoding("utf-8");
        List fileList = null;
        try {
            fileList = upload.parseRequest(request);
        } catch (FileUploadException ex) {
            return;
        }

        Iterator it = fileList.iterator();
        String name = "";
        String extName = "";
        while (it.hasNext()) {
            FileItem item = it.next();
            if (!item.isFormField()) {
                name = item.getName();
                long size = item.getSize();
                String type = item.getContentType();
                System.out.println(size + " " + type);
                if (name == null || name.trim().equals("")) {
                    continue;
                }

                //     : 
                if (name.lastIndexOf(".") >= 0) {
                    extName = name.substring(name.lastIndexOf("."));
                }

                File file = null;
                //                
                do {
                    //     :
                    name = UUID.randomUUID().toString();
                    file = new File(savePath + name + extName);
                } while (file.exists());
                File saveFile = new File(savePath + name + extName);
                try {
                    item.write(saveFile);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        response.getWriter().print(name + extName);
    }
}

WEB. XML 설정 은 다음 과 같 습 니 다.
	
		upload
		com.zcb.servlet.Upload
	
	
		upload
		/servlet/Upload
	
  
    index.jsp
  

좋은 웹페이지 즐겨찾기