Flex + Java Servlet 파일 업로드 인 스 턴 스

자원 은 모두 인터넷 에서 나온다.이 인 스 턴 스 는 Flex 와 자바 servlet 를 사용 하여 파일 을 업로드 하 는 것 을 보 여 줍 니 다.
사전에 준비 하면 도착한다
common - fileupload - 1.1.1. jar 와 common - io - 1.2. jar 두 개의 가방 을 다운로드 합 니 다.
프론트 플 렉 스 코드:

<?xml version="1.0" encoding="utf-8"?>  
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" xmlns="*" creationComplete="init();">  
<mx:Script>  
<![CDATA[  
import flash.net.FileReference;  
import mx.controls.Alert;  
import mx.events.CloseEvent;  
import flash.events.*;  
 
private var file: FileReference;  
 
private function init(): void{  
Security.allowDomain("*");  
file = new FileReference();  
file.addEventListener(ProgressEvent.PROGRESS, onProgress);  
file.addEventListener(Event.SELECT, onSelect);  
file.addEventListener(Event.COMPLETE, completeHandle);  
}  
 
private function completeHandle(event:Event):void{  
    Alert.show("   ,    ");  
}  
 
private function upload(): void{  
var imageTypes:FileFilter = new FileFilter("Images (*.jpg, *.jpeg, *.png)", "*.jpg;*.jpeg;*.png");  
var allTypes:Array = new Array(imageTypes);  
file.browse(allTypes);  
file.browse();  
}  
private function onSelect(e: Event): void{  
Alert.show("   " + file.name + " (  "+Math.round(file.size)+"   )?",  
"    ",  
Alert.YES|Alert.NO,  
null,  
proceedWithUpload);  
}  
 
private function onProgress(e: ProgressEvent): void{  
lbProgress.text = "     " + e.bytesLoaded  
+ "   ,  " + e.bytesTotal + "   ";  
var proc: uint = e.bytesLoaded / e.bytesTotal * 100;  
bar.setProgress(proc, 100);  
bar.label= "    : " + " " + proc + "%";  
}  
 
private function proceedWithUpload(e: CloseEvent): void{  
if (e.detail == Alert.YES){  
var request: URLRequest = new URLRequest("http://localhost:8080/FileUploaded/FileUploaded");  
try {  
file.upload(request);  
} catch (error:Error) {  
trace("    ");  
}  
 
}  
}  
]]>  
</mx:Script>  
  
<mx:Canvas width="100%" height="100%" x="10" y="170" fontSize="15">  
<mx:VBox width="100%" horizontalAlign="center">  
<mx:Label id="lbProgress" text="  "/>  
<mx:ProgressBar id="bar" labelPlacement="bottom" themeColor="#F20D7A"  
minimum="0" visible="true" maximum="100" label="    : 0%"  
direction="right" mode="manual" width="200"/>  
  
<mx:Button label="    " click="upload();"/>  
</mx:VBox>  
</mx:Canvas>  
</mx:Application>  


http://localhost:8080/FileUploaded/FileUploaded
니 가 쓴 servlet 경로 야.
다음은 자바 서 블 릿:
package upload;   
import java.io.File;   
import java.io.IOException;   
import java.io.PrintWriter;   
import java.util.Iterator;   
import java.util.List;   
  
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 crystal   
 */   
public class FileUploaded extends HttpServlet {   
  
    /**   
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.   
     * @param request servlet request   
     * @param response servlet response   
     */   
    //             
  
    private String uploadPath = "d:\\a\\";   
  
//             
  
    private int maxPostSize = 100 * 1024 * 1024;   
  
    public FileUploaded() {   
        super();   
    }   
  
    public void destroy() {   
        super.destroy();   
    }   
  
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)   
            throws ServletException, IOException {   
        System.out.println("Access !");   
        response.setContentType("text/html;charset=UTF-8");   
        PrintWriter out = response.getWriter();   
  
//            
  
        DiskFileItemFactory factory = new DiskFileItemFactory();   
        factory.setSizeThreshold(4096);   
        ServletFileUpload upload = new ServletFileUpload(factory);   
        upload.setSizeMax(maxPostSize);   
        try {   
            List fileItems = upload.parseRequest(request);   
            Iterator iter = fileItems.iterator();   
            while (iter.hasNext()) {   
                FileItem item = (FileItem) iter.next();   
                if (!item.isFormField()) {   
                    String name = item.getName();   
                    System.out.println(name);   
                    try {   
                        item.write(new File(uploadPath + name));   
                       // SaveFile s = new SaveFile();   
  
                       // s.saveFile(name);   
  
                    } catch (Exception e) {   
                        e.printStackTrace();   
                    }   
                }   
            }   
        } catch (FileUploadException e) {   
            e.printStackTrace();   
            System.out.println(e.getMessage() + "  ");   
        }   
    }   
  
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">  
  
    /**   
     * Handles the HTTP <code>GET</code> method.   
     * @param request servlet request   
     * @param response servlet response   
     */   
    protected void doGet(HttpServletRequest request, HttpServletResponse response)   
            throws ServletException, IOException {   
        processRequest(request, response);   
    }   
  
    /**   
     * Handles the HTTP <code>POST</code> method.   
     * @param request servlet request   
     * @param response servlet response   
     */   
    protected void doPost(HttpServletRequest request, HttpServletResponse response)   
            throws ServletException, IOException {   
        processRequest(request, response);   
    }   
  
    /**   
     * Returns a short description of the servlet.   
     */   
    public String getServletInfo() {   
        return "Short description";   
    }   
    // </editor-fold>  
  
}

Servlet 에 접근 하려 면 WEB - INF / web. xml 에 다음 과 같은 xml 문 구 를 추가 해 야 합 니 다. [< 웹 - app > 에서]

<!-- For file uploaded -->  
   <servlet>  
        <servlet-name>FileUploaded</servlet-name>  
        <servlet-class>upload.FileUploaded</servlet-class>  
    </servlet>  
  
    <servlet-mapping>  
        <servlet-name>FileUploaded</servlet-name>  
        <url-pattern>/FileUploaded</url-pattern>  
    </servlet-mapping>  

참고:
[url]http://blog.csdn.net/meteorlWJ/archive/2008/06/01/2450234.aspx [/url]
[url]http://swingchen.bokee.com/5943371.html [/url]
[url]http://www.cnblogs.com/dannyr/archive/2006/11/13/559006.html [/url]
원본 코드 다운로드
http://commons.apache.org

좋은 웹페이지 즐겨찾기