flex 端 面板
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" xmlns:dateUtil="net.util.*"
x="500" y="200" width="569" height="738" creationComplete="init()" layout="absolute" fontSize="14" verticalAlign="top">
<mx:Panel x="69" y="10" width="433" height="527" layout="absolute" title="图片上传">
<mx:Label text="主标题" x="39" y="16"/>
<mx:Label text="副标题" x="39" y="54"/>
<mx:TextInput x="116" y="16" width="201" id="mainTitleInput" text="{mainTitle}"/>
<mx:TextInput x="117" y="54" width="201" id="subTitleInput" text="{subTitle}"/>
<mx:TextInput x="117" y="92" width="201" id="linkInput" text="{link}"/>
<mx:TextInput x="118" y="128" width="201" id="picInput" text="{picName}" editable="false"/>
<mx:Button x="178" y="445" label="保存" id="uploadButton"/>
<mx:Label text="链接" x="53" y="94"/>
<mx:Label text="图片" x="53" y="130"/>
<mx:TextInput x="100" y="285" width="201" id="csmallPic" text="" visible="false"/>
<mx:Button label="选择图片"
x="324"
y="130" id="small"/>
<mx:Image id="img"
width="316"
height="253"
x="54"
y="173" httpStatus="img_httpStatus(event);" source="{contentImage}"/>
<mx:Script>
<!--[CDATA[
import flash.events.*;
import mx.controls.Alert;
import mx.managers.CursorManager;
import mx.managers.PopUpManager;
private var file:FileReference;
private var byteArray:ByteArray;
private var bitmapData:BitmapData;
private var loader:Loader=new Loader();
[Bindable]
public var bannerId:String;
[Bindable]
public var cid:String;
[Bindable]
public var mainTitle:String;
[Bindable]
public var link:String;
[Bindable]
public var subTitle:String;
[Bindable]
public var contentImage:String;
[Bindable]
public var bannerTemplet:String;
[Bindable]
public var picName:String=" ";
public var bigName:String=new CreateImageName().getName(1);
public var urls:String=URLconst.uploadStartURL+bigName+URLconst.uploadEndURL;
public var isAdd:Boolean;
public var picUpload:PicUpload;
private function init():void{
picUpload=new PicUpload(small,
img,
picInput,
csmallPic,
uploadButton,
urls,"uploadsfinished");
picUpload.addEventListener("uploadsfinished",uploadsfinished);
}
public function uploadsfinished(event:Event):void{
// this.dispatchEvent(new Event("saveBannerContent"));
Alert.show("上传完成");
}
//监听从远程FTP取图片是否成功
private function img_httpStatus(evt:HTTPStatusEvent):void {
switch (evt.status) {
case 200:
// Valid image, do nothing.
break;
case 404:
// Invalid image, PANIC!
Alert.show("无效图片", evt.status.toString());
break;
default:
Alert.show(evt.toString(), evt.status.toString());
break;
}
}
]]-->
</mx:Script>
</mx:Panel>
</mx:Application>
封装后的组件:
package
{
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.Loader;
import flash.events.*;
import flash.net.FileFilter;
import flash.net.FileReference;
import flash.net.URLRequest;
import flash.system.Security;
import flash.utils.ByteArray;
import mx.controls.Alert;
import mx.controls.Button;
import mx.controls.Image;
import mx.controls.TextInput;
import mx.managers.CursorManager;
public class PicUpload
{
//Events
public var completeEvent:Event;
//UI Vars
private var _browsebutton:Button;
private var _uploadbutton:Button;
private var picInput:TextInput;
private var csmallPic:TextInput;
private var img:Image;
//File Reference Vars
[Bindable]
private var file:FileReference;
private var request:URLRequest;
private var byteArray:ByteArray;
private var bitmapData:BitmapData;
private var loader:Loader=new Loader();
private var _maxFileSize:Number=302400; //bytes
//File Filter vars
private var imageTypes:FileFilter = new FileFilter("Images (*.jpg; *.jpeg; *.gif; *.png)" ,"*.jpg; *.jpeg; *.gif; *.png");
//private var videoTypes:FileFilter = new FileFilter("Flash Video Files (*.flv)","*.flv");
//private var documentTypes:FileFilter = new FileFilter("Documents (*.pdf)",("*.pdf"));
private var allTypes:Array = new Array(imageTypes);//,videoTypes,documentTypes);
//config vars
private var _url:String;
private var _rollBack:String="";
public function PicUpload(browseButton:Button,
imge:Image,
disInput:TextInput,
visInput:TextInput,
uploadButton:Button,
url:String,
rollBack:String){
_browsebutton=browseButton;
img=imge;
picInput=disInput;
csmallPic=visInput;
_uploadbutton=uploadButton;
_url=url;
_rollBack=rollBack;
init();
}
private function init():void{
Security.allowDomain("*");
file=new FileReference();
file.addEventListener(Event.COMPLETE, fileReferenceCompleteHandler);
file.addEventListener(Event.SELECT, fileReferenceSelectHandler);
_browsebutton.addEventListener(MouseEvent.CLICK, choose);
_uploadbutton.addEventListener(MouseEvent.CLICK, proceedWithUpload);
request=new URLRequest
request.url=_url;
}
//选择上传的图片
private function choose(event:MouseEvent):void
{
file.browse(allTypes);
}
//上传图片到服务器
private function proceedWithUpload(event:MouseEvent):void
{
if(csmallPic.text!=""){
file.upload(request);
file.addEventListener(IOErrorEvent.IO_ERROR,errorHandler);//文件失败上传监听事件
file.addEventListener(Event.COMPLETE,doFileUploadComplete);//文件成功上传监听事件
file.addEventListener(SecurityErrorEvent.SECURITY_ERROR,securityErrorHandler);
file.addEventListener(HTTPStatusEvent.HTTP_STATUS,httpStatusHandler);
}
}
//载入本地图片
private function fileReferenceCompleteHandler(e:Event):void
{
byteArray=file.data;
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loaderCompleteHandler);
loader.loadBytes(byteArray);
}
//图片载入完成显示在预览框中
private function loaderCompleteHandler(e:Event):void
{
var bitmap:Bitmap=Bitmap(loader.content);
bitmapData=bitmap.bitmapData;
img.source=bitmap;
}
//选择文件动作监听
private function fileReferenceSelectHandler(e:Event):void
{
var msg:String ="";
if (checkFileSize(file.size)){
csmallPic.text=file.name;
picInput.text=file.name;
file.load();
} else {
msg += file.name + " 大小超过限制了. /n";
Alert.show(msg + "图片最大允许: " + Math.round(_maxFileSize / 1024) + " kb","图片大小超过限制",4,null).clipContent;
}
}
//验证图片大小
private function checkFileSize(filesize:Number):Boolean{
var r:Boolean = false;
if (filesize > _maxFileSize){
r = false;
trace("false");
}else if (filesize <= _maxFileSize){
r = true;
trace("true");
}
if (_maxFileSize == 0){
r = true;
}
return r;
}
//上传失败处理事件
private function errorHandler(evt:IOErrorEvent):void{
Alert.show(evt.text,"上传失败,检查网络");
}
//上传成功处理
private function doFileUploadComplete(evt:Event):void{
if(_rollBack!=""){
this.dispatchEvent(new Event(_rollBack));
}
}
private function securityErrorHandler(event:SecurityErrorEvent):void{
mx.controls.Alert.show(event.text,"Security Error",0);
}
private function httpStatusHandler(event:HTTPStatusEvent):void {
if (event.status != 200){
mx.controls.Alert.show(event.toString(),"上传错误",0);
}
}
}
}
其他工具类:
package
{
import mx.formatters.DateFormatter;
public class CreateImageName
{
public function getName(i:int):String
{
// var random:String=Math.ceil(Math.random() * 9)+""+i+ ".jpg";
var random:String=i+"";
var time:Date=new Date();
var fr:DateFormatter=new DateFormatter();
fr.formatString="YYYYMMDDJJNNSS";
var imageName:String=fr.format(time)+random;
// return random;
return "/promotions/"+imageName;
}
}
}
package
{
public class URLconst
{
public static var uploadStartURL:String="http://172.16.50.147:80/backWeb/photoUpload";
public static var uploadEndURL:String=".html";
}
}
java 端 控制器
package net.shopin.web;
import cn.com.infosec.icbc.ReturnValue;
import net.shopin.util.FTPUtil;
import net.shopin.util.FtpServerConf;
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;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
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;
/**
* 图片上传控制器
*/
@Controller
public class PhotoUploadController {
@Autowired
FtpServerConf ftpServer;
// 限制文件的上传大小
private int maxPostSize = 100 * 1024 * 1024;
@RequestMapping(value = "/photoUpload/{fileDic}/{name}.html", method = {RequestMethod.GET, RequestMethod.POST})
public String register(Model m, @PathVariable("name") String name, @PathVariable("fileDic") String fileDic, HttpServletRequest request) {
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(4096);
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setSizeMax(maxPostSize);
OutputStream out = null;
try {
List fileItems = upload.parseRequest(request);
Iterator iter = fileItems.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (!item.isFormField()) {
String filename = item.getName();
// System.out.println("-------" + filename);
System.out.println("---name----" + name);
name = name + ".jpg";
// 保存图片到MongoD
// MongodServiceImpl mongoDAO = new MongoService("shopin_db_img", "img");
// mongoDAO.saveFile(item.get(), "20090103.jpg");
// String fileDic = "promotions";
// 保存图片到FTP
FTPUtil.saveToFTP(out, fileDic, name, item, ftpServer.getHost(), ftpServer.getUsername(), ftpServer.getPassword());
}
}
} catch (FileUploadException e) {
e.printStackTrace();
System.out.println(e.getMessage() + "结束");
}
return "index";
}
FTP 操作工具类
package net.shopin.util;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.commons.fileupload.FileItem;
import com.enterprisedt.net.ftp.FTPException;
import com.enterprisedt.net.ftp.FileTransferClient;
import org.springframework.beans.factory.annotation.Autowired;
public class FTPUtil {
public static void saveToFTP(OutputStream out, String fileDic, String filename,
FileItem item, String host, String username, String password) {
FileTransferClient ftp = null;
try {
ftp = new FileTransferClient();
ftp.setRemoteHost(host);
ftp.setUserName(username);
ftp.setPassword(password);
ftp.setRemotePort(21);
ftp.connect();
ftp.changeDirectory(fileDic);
if (!ftp.exists(filename)) {
out = ftp.uploadStream(filename);
out.write(item.get());
}
// ftp.uploadFile("d://shopin//report.sql", "test.jpg");
// ftp.createDirectory("test");
} catch (FTPException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
ftp.disconnect();
} catch (FTPException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void delFromFTP(String fileDic, String filename,
String host, String username, String password) {
FileTransferClient ftp = null;
try {
ftp = new FileTransferClient();
ftp.setRemoteHost(host);
ftp.setUserName(username);
ftp.setPassword(password);
ftp.setRemotePort(21);
ftp.connect();
ftp.changeDirectory(fileDic);
boolean flag = ftp.exists(filename);
// System.out.println("--------"+flag);
if (flag) {
ftp.deleteFile(filename);
}
// ftp.uploadFile("d://shopin//report.sql", "test.jpg");
// ftp.createDirectory("test");
} catch (FTPException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
ftp.disconnect();
} catch (FTPException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
转自:http://lqw.javaeye.com/blog/607867