Java需要用到的包http://download.csdn.net/download/duanjingyu/2296147
Java端代码
package com.fileupload;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.Charset;
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;
public class FileUpload extends HttpServlet {
// 限制文件的上传大小
private int maxPostSize = 100 * 1024 * 1024;
public FileUpload() {
super();
}
public void destroy() {
super.destroy();
}
protected void processRequest(HttpServletRequest request,
HttpServletResponse response) throws Exception {
System.out.println("开始!");
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(4096);
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setSizeMax(maxPostSize);
try {
request.setCharacterEncoding("UTF-8");
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);
String uploadPath = null;
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
uploadPath = request.getRealPath("/");
System.out.println(uploadPath);
item.write(new File(uploadPath +"uploadfile/"+ name));
out.print(name+"上传成功");
}
}
} catch (FileUploadException e) {
e.printStackTrace();
}
System.out.println("结束");
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
try {
processRequest(request, response);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
try {
processRequest(request, response);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String getServletInfo() {
return "Short description";
}
}
<?xml version = '1.0' encoding = 'UTF-8'?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee">
<description>Empty web.xml file for Web Application</description>
<servlet>
<servlet-name>FileUpload</servlet-name>
<servlet-class>com.fileupload.FileUpload</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FileUpload</servlet-name>
<url-pattern>/FileUpload</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>35</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>FlexUpload.html</welcome-file>
</welcome-file-list>
</web-app>
flex应用端代码
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/<a href="http://lib.csdn.net/base/10" class='replace_word' title="Apache Spark知识库" target='_blank' style='color:#df3434; font-weight:bold;'>Spark</a>"
xmlns:mx="library://ns.adobe.com/flex/mx"
xmlns="*" creationComplete="init();" >
<fx:Script>
<!--[CDATA[
import flash.events.*;
import flash.net.FileReference;
import mx.controls.Alert;
import mx.events.CloseEvent;
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
private var file: FileReference;
private function init(): void{
// Security.loadPolicyFile("http://127.0.0.1:8080/FileUpload/crossdomain.xml");//异域服务器使用
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(event:Event): void{
var imageTypes:FileFilter = new FileFilter("Images (*.jpg, *.jpeg, *.png)", "*.jpg;*.jpeg;*.png");
var allTypes:Array = new Array(imageTypes);
file.browse(allTypes);
}
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://127.0.0.1:8080/FileUpload/FileUpload");
try {
file.upload(request);
file.addEventListener(IOErrorEvent.IO_ERROR,onError);
file.addEventListener(ResultEvent.RESULT,resuleEvent);
} catch (error:Error) {
trace("上传失败");
}
}
}
private function resuleEvent(event:ResultEvent):void{
Alert.show(event.message.body.toString());
}
private function onError(event:IOErrorEvent):void{
Alert.show("IO错误"+event.toString());
}
]]-->
</fx: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"
minimum="0" visible="true" maximum="100" label="当前进度: 0%"
direction="right" mode="manual" width="200"/>
<mx:Button label="上传文件" click="upload(event);"/>
</mx:VBox>
</mx:Canvas>
</s:Application>