Flex图片上传

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();
}
}
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 UniApp 中实现多图片上传可以使用以下步骤: 1. 在 `pages` 目录下创建一个新的页面,比如 `UploadImages.vue`。 2. 在 `UploadImages.vue` 中添加一个用于显示已上传图片的容器,可以使用 `uni-image` 组件。 3. 添加一个按钮或其他触发上传的元素。 4. 在点击触发元素时,调用 `uni.chooseImage` 方法选择需要上传的图片,该方法会返回选中的图片路径。 5. 使用 `uni.uploadFile` 方法将选中的图片上传到服务器。可以使用循环遍历的方式逐个上传图片,或者将多个图片打包成一个文件再上传。 6. 在上传成功的回调中,将服务器返回的图片路径保存到本地或显示在页面上。 以下是一个示例代码: ```html <template> <view class="container"> <view class="uploaded-images"> <uni-image v-for="(image, index) in uploadedImages" :src="image" :key="index"></uni-image> </view> <uni-button @click="chooseImages">选择图片</uni-button> </view> </template> <script> export default { data() { return { uploadedImages: [] // 已上传的图片路径 }; }, methods: { chooseImages() { uni.chooseImage({ count: 9, // 最多可选择的图片数量 success: (res) => { const tempFilePaths = res.tempFilePaths; // 选中的图片路径数组 this.uploadImages(tempFilePaths); } }); }, uploadImages(images) { images.forEach((image) => { uni.uploadFile({ url: 'https://your-server.com/upload', // 上传的服务器接口地址 filePath: image, name: 'file', success: (res) => { // 上传成功,保存图片路径 const data = JSON.parse(res.data); this.uploadedImages.push(data.path); } }); }); } } }; </script> <style> .container { padding: 20px; } .uploaded-images { display: flex; flex-wrap: wrap; } .uni-image { margin-right: 10px; margin-bottom: 10px; } </style> ``` 上述代码中,点击 "选择图片" 按钮会调用 `uni.chooseImage` 方法选择图片,并通过 `uni.uploadFile` 方法分别上传到服务器,上传成功后将返回的图片路径保存到 `uploadedImages` 数组中,并通过 `v-for` 指令渲染出已上传的图片。 请注意替换示例代码中的上传服务器接口地址为实际的后端接口地址,并根据实际需求进行相应的调整。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值