1.java后端的servlet:
FileUploadServlet.java
package com.topinfo.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;
import org.springframework.stereotype.Service;
@Service
public class FileUploadServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 2713969028284025936L;
// 限制文件的上传大小
private int maxPostSize = 100 * 1024 * 1024;
public FileUploadServlet() {
super();
}
public void destroy() {
super.destroy();
}
private String uploadPath="";
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
int status = 0;
// 定义文件的上传路径
uploadPath = this.getServletConfig().getServletContext()
.getRealPath("/")
+ "\\upload\\";
// 得到用户需要保存的服装的id
String dressId = request.getParameter("dressID");
// System.out.println(dressId);
// 保存文件到服务器中
response.setContentType("text/html; charset=UTF-8");
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();
name = request.getParameter("filename");
//System.out.println(name);
try {
item.write(new File(uploadPath + name));
} catch (Exception e) {
e.printStackTrace();
}
}
}
} catch (FileUploadException e) {
e.printStackTrace();
status = -1;
}
String show= "";
if(status==0){
show="企业概述图片上传成功!";
}else if(status==1){
show="企业概述图片上传失败!";
}
PrintWriter out = response.getWriter();
out.print(show);
out.close();
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
public void init() throws ServletException {
// Put your code here
}
public boolean delImge(String value){
boolean b = true;
try{
String path = this.getClass().getResource("/").toString();
path = path.substring(path.indexOf("file:/")+6,path.indexOf("WEB-INF"));
path+="upload/";
File file = new File(path + value);
if(file!=null&&file.exists()){
file.delete();
}else{
b = false;
}
}catch(Exception e){
System.out.println(e);
b = false;
}
return b;
}
}
2.flex端的组建:
文件upLoader.mxml
<?xml version="1.0" encoding="utf-8"?>
<s:Group xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx" creationComplete="module1_creationCompleteHandler(event)" xmlns:components="com.topinfo.components.*">
<fx:Script>
<![CDATA[
import flash.globalization.DateTimeFormatter;
import mx.controls.Alert;
import mx.controls.DateField;
import mx.core.FlexGlobals;
import mx.events.CloseEvent;
import mx.events.FlexEvent;
import mx.formatters.DateFormatter;
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
import spark.formatters.DateTimeFormatter;
private var file:FileReference;
private var _filepath:String;
private var filename:String;
public function set filepath(value:String):void{
this._filepath = value;
getfilepath = "http://"+FlexGlobals.topLevelApplication.fullUrl+"/fysupervise/upload/"+value;
imgshow.source = getfilepath;
}
public function get filepath():String{
if(_filepath!=null){
getfilepath = "http://"+FlexGlobals.topLevelApplication.fullUrl+"/fysupervise/upload/"+_filepath;
imgshow.source = getfilepath;
}
return this._filepath;
}
[Bindable]
private var getfilepath:String;
protected function module1_creationCompleteHandler(event:FlexEvent):void
{
// TODO Auto-generated method stub
Security.allowDomain("*");
file = new FileReference();
file.addEventListener(ProgressEvent.PROGRESS, onProgress);
file.addEventListener(Event.SELECT, onSelect);
file.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA,show);
}
//---------------------上传部分开始--------------------
private function onSelect(e:Event): void{
proceedWithUpload();
//Alert.show("上传 " + file.name + " (共 "+Math.round(file.size)+" 字节)?",
// "确认上传",
// Alert.YES|Alert.NO,
// null,
// proceedWithUpload);
}
private function onProgress(e:ProgressEvent): void{
var proc: uint = e.bytesLoaded / e.bytesTotal * 100;
bar.setProgress(proc, 100);
bar.label= "当前进度: " + " " + proc + "%";
if(proc == 100){
bar.visible = false;
bar.label= "当前进度: 0%";
this.filepath = filename;
}
}
private function proceedWithUpload(): void{
filename = createFileName(file.name);
var request: URLRequest = new URLRequest("http://"+FlexGlobals.topLevelApplication.fullUrl+"/fysupervise/FileUploadServlet?filename="+filename);
try {
file.upload(request);
bar.visible = true;
} catch (error:Error) {
trace("上传失败");
}
}
protected function createFileName(value:String):String{
var df:DateFormatter = new DateFormatter();
df.formatString = "YYYYMMDDJJNNSS"
var lastname:String = value.substr(value.indexOf("."),4);
var firstname:String = df.format(new Date());
return firstname+lastname;
}
protected function add_dwqj_clickHandler(event:MouseEvent):void
{
// TODO Auto-generated method stub
file.browse();
}
//---------------------上传部分结束--------------------
private function show(event:DataEvent):void{
Alert.show(event.data.toString());
}
private function deleteImg():void{
if(_filepath!=null)
fileService.delImge(_filepath);
}
protected function fileService_resultHandler(event:ResultEvent):void
{
// TODO Auto-generated method stub
var b:Boolean = event.result as Boolean;
if(b){
Alert.show("删除成功");
imgshow.source = null;
_filepath=null;
}else{
Alert.show("删除失败");
}
}
private function delFault(event:FaultEvent):void{
Alert.show("删除失败"+event);
}
]]>
</fx:Script>
<fx:Declarations>
<!-- 将非可视元素(例如服务、值对象)放在此处 -->
<s:RemoteObject id="fileService" destination="fileUploadService" result="fileService_resultHandler(event)" fault="delFault(event)" />
</fx:Declarations>
<s:VGroup horizontalAlign="center" verticalAlign="middle" gap="10">
<s:SkinnableContainer backgroundColor="#ffffff" width="330" height="228">
<s:HGroup width="100%" height="100%" horizontalAlign="center" verticalAlign="middle">
<s:Image id="imgshow" source="{getfilepath}" width="305" height="200" />
</s:HGroup>
</s:SkinnableContainer>
<s:Label text="请选择jpg、png格式,且文件尺寸为305×200的图片" />
<s:HGroup width="100%" height="30" horizontalAlign="center" verticalAlign="middle">
<mx:ProgressBar id="bar" labelPlacement="bottom" minimum="0" maximum="100" label="当前进度: 0%"
direction="right" mode="manual" width="170" visible="false"/>
<components:functionButton image="/res/images/shanchu.png" imagenormal="/res/images/shanchuhover.png" id="del_dwqj" text="清除" click="deleteImg()" />
<components:functionButton image="/res/images/queding.png" imagenormal="/res/images/quedinghover.png" id="add_dwqj" text="上传" click="add_dwqj_clickHandler(event)" />
</s:HGroup>
</s:VGroup>
</s:Group>
通过这2个文件结合就可以在flex端界面上实现上传功能了,这里给的例子是上传图片示范。