一、页面中的配置
<aebiz:file property="bigPicData" fileType="<%=FileConst.FILE_TYPE_PICTURE%>" maxSize="1" width="115px" height="115px" value="<%=bean.getBigPicture()%>"/>
// 获取页面输出的方法
public String getFileStr() {
// HttpSession session = this.pageContext.getSession();
HttpServletRequest request = (HttpServletRequest) this.pageContext
.getRequest();
// 解析图片宽度,将"px"去掉,只去数字部分
if (!StringUtil.isEmpty(width)) {
width = getNumbers(width);
if (StringUtil.isEmpty(width)) {
width = "100";
}
this.setWidth(width);
}
// 解析图片高度,将"px"去掉,只去数字部分
if (!StringUtil.isEmpty(height)) {
height = getNumbers(height);
if (StringUtil.isEmpty(height)) {
height = "100";
}
this.setHeight(height);
}
// 拼写文件全路径
if (!StringUtil.isEmpty(value)) {
ActionRequest arequest = (ActionRequest) request
.getAttribute("arequest");
if (arequest != null) {
urlPath = arequest.getImage(value);
setUrlPath(urlPath);
} else {
// 如果文件路径不包含 http之类的,则拼写
if (value.indexOf("http") == -1 && value.indexOf("HTTP") == -1
&& value.indexOf("https") == -1
&& value.indexOf("HTTPS") == -1) {
String serverName = "http://" + request.getServerName();
if (80 != request.getServerPort()) {
serverName = serverName + ":" + request.getServerPort();
}
String contextPath = request.getContextPath();
if (!StringUtil.isEmpty(contextPath)) {
if (!contextPath.startsWith("/")) {
contextPath = "/" + contextPath + "/";
} else {
contextPath = contextPath + "/";
}
} else {
contextPath = "/";
}
//urlPath = serverName + contextPath + value;
if (StringUtil.isEmpty(FileUtil.IMAGEROOT)) {
FileUtil.IMAGEROOT = ShopApplicationResource.shopResource
.getString("image.webroot");
}
String returnImage = FileUtil.IMAGEROOT;
urlPath = returnImage +"/" + value;
// urlPath = serverName + "/" + request.getContextPath() +
// "/" + value;
setUrlPath(urlPath);
} else {
setUrlPath(value);
}
}
}
// 设置最大尺寸,如果没有传过来,则默认为1T
if (StringUtil.isEmpty(this.maxSize)) {
maxSize = (1024 * 1024) + "";
} else {
maxSize = getNumbers(maxSize);
}
setMaxSize(maxSize);
// HttpSession session = this.pageContext.getSession();
StringBuffer str = new StringBuffer("");
// 上传的文件类型为图片
if (FileConst.FILE_TYPE_PICTURE.equals(this.fileType)) {
str.append("<div class='pic-updiv' style='width:").append(
this.width).append("px;height:").append(this.height)
.append("px;' id='").append(this.property).append(
"Preview' ></div> \r\n");
str.append("<div style='width:").append(this.width).append(
"px;' align=center> \r\n");
str.append("<a class='pic-upload' id='").append(this.property)
.append("a'> \r\n");
str.append("<input type='file' name='").append(this.property)
.append("InputFile' id='").append(this.property).append(
"InputFile'> \r\n");
str.append("</a> \r\n");
str.append("<div class='pic-upwait' id='").append(this.property)
.append("adiv'></div> \r\n");
str.append("</div> \r\n");
} else {
// 上传的文件类型为除图片之外的所有类型
str.append("<div class='file-updiv'> \r\n");
str.append("<a class='file-upload' id='").append(this.property)
.append("a'> \r\n");
str.append("<input type='file' name='").append(this.property)
.append("InputFile' id='").append(this.property).append(
"InputFile'> \r\n");
str.append("</a> \r\n");
str.append("<div class='file-upwait' id='").append(this.property)
.append("adiv'></div> \r\n");
if (FileConst.FILE_TYPE_EXCEL.equals(this.fileType)) {
str.append("<span id='").append(this.property).append(
"Span' class='file-span'>请选择EXCEL文件</span> \r\n");
} else if (FileConst.FILE_TYPE_WORD.equals(this.fileType)) {
str.append("<span id='").append(this.property).append(
"Span' class='file-span'>请选择WORD文件</span> \r\n");
} else if (FileConst.FILE_TYPE_ZIP.equals(this.fileType)) {
str.append("<span id='").append(this.property).append(
"Span' class='file-span'>请选择压缩文件</span> \r\n");
} else {
str.append("<span id='").append(this.property).append(
"Span' class='file-span'></span> \r\n");
}
str.append("</div> \r\n");
}
// 拼写隐藏域,用来传递值
str.append("<input type='hidden' name='").append(this.property).append(
"remove' id='").append(this.property).append(
"remove' value='false'/> \r\n");
str.append("<input type='hidden' name='").append(this.property).append(
"OldUrlPath' id='").append(this.property).append(
"OldUrlPath' value='").append(this.value).append("'/> \r\n");
str.append("<input type='hidden' name='").append(this.property).append(
"OldRealPath' id='").append(this.property).append(
"OldRealPath' value='").append(this.urlPath).append("'/> \r\n");
str.append("<input type='hidden' name='").append(this.property).append(
"FileUrl' id='").append(this.property).append(
"FileUrl' value=''/> \r\n");
if (!StringUtil.isEmpty(value)) {
str.append("<input type='hidden' name='").append(this.property)
.append("editUrl' id='").append(this.property).append(
"editUrl' value='true'/> \r\n");
} else {
str.append("<input type='hidden' name='").append(this.property)
.append("editUrl' id='").append(this.property).append(
"editUrl' value='false'/> \r\n");
}
if (!StringUtil.isEmpty(this.urlPath)) {
try {
// URL url = new URL(this.urlPath);
// BufferedImage image = ImageIO.read(url);
BufferedImage image = ImageIO.read(new File(this.urlPath));
int width = image.getWidth();
int height = image.getHeight();
str.append("<input type='hidden' name='").append(this.property)
.append("wh' id='").append(this.property).append(
"wh' value='").append(width).append(",")
.append(height).append("'/> \r\n");
} catch (IOException e) {
str.append("<input type='hidden' name='").append(this.property)
.append("wh' id='").append(this.property).append(
"wh' value=''/> \r\n");
}
} else {
str.append("<input type='hidden' name='").append(this.property)
.append("wh' id='").append(this.property).append(
"wh' value=''/> \r\n");
}
// 调用各个类型的JS
if (FileConst.FILE_TYPE_PICTURE.equals(this.fileType)) {
str.append("<script> ajaxChosePic('").append(this.property).append(
"','").append(width).append("','").append(height).append(
"','").append(maxSize).append("'); </script> \r\n");
} else if (FileConst.FILE_TYPE_EXCEL.equals(this.fileType)) {
str.append("<script> ajaxChoseExcel('").append(this.property)
.append("','").append(maxSize).append("'); </script> \r\n");
} else if (FileConst.FILE_TYPE_WORD.equals(this.fileType)) {
str.append("<script> ajaxChoseWord('").append(this.property)
.append("','").append(maxSize).append("'); </script> \r\n");
} else if (FileConst.FILE_TYPE_ZIP.equals(this.fileType)) {
str.append("<script> ajaxChoseZip('").append(this.property).append(
"','").append(maxSize).append("'); </script> \r\n");
}
return str.toString();
}
二、通过ajaxChosePic函数进行标签配置及ajaxupload配置
var ajaxChosePic = function(inputName,widthStr,heightStr,fileSize){
var oldPicPath = document.getElementsByName(inputName+"OldRealPath")[0].value;
var picwh = document.getElementsByName(inputName+"wh")[0].value;
var isEdit = document.getElementsByName(inputName+"editUrl")[0].value;
if(oldPicPath != '' && oldPicPath != ' ' && oldPicPath != null && oldPicPath != 'null' && "true" == isEdit){
var picWidth = "0";
var picHeight = "0";
if(picwh != '' && picwh != ' '){
var wh = picwh.split(',');
if(wh != null && wh.length >0){
picWidth = wh[0];
picHeight = wh[1];
}
}
initPic(inputName,oldPicPath,picWidth,picHeight);
}
new AjaxUpload(inputName+"InputFile",{
action:contentPath+"/file/fileup.do?actionType=upload&fileSize="+fileSize+"&ranNum="+Math.random(),
autoSubmit:true,
name:inputName,
onSubmit:function(file,extension){
if (extension && /^(pdf|jpg|png|jpeg|gif|PDF|JPG|PNG|JPEG|GIF)$/.test(extension)){
hideFileUp(inputName+"a");
showFileUp(inputName+"adiv")
document.getElementById(inputName+"Preview").style.background = "url("+contentPath + "/img/fileUpload/tpwait.gif) center center no-repeat";
} else {
//$("#loading").html("你所选择的文件不受系统支持");
//$("#loading").show();
alert("你所选择的文件不受系统支持")
return false;
}
},
onComplete: function(file,response){
var dataobj=eval("(" + response + ")");
var errorMessage = dataobj.rsp.errorMessage;
if(errorMessage != '' && errorMessage != ' '){
showFileUp(inputName + "a");
hideFileUp(inputName + "adiv");
alert("文件上传失败,文件大小最大可传"+fileSize + "M");
document.getElementById(inputName+"Preview").innerHTML="";
document.getElementById(inputName+"Preview").style.background = "url("+contentPath + "/img/fileUpload/zwtp.png) center center no-repeat";
document.getElementsByName(inputName+"FileUrl")[0].value="";
document.getElementById(inputName+"Preview").setAttribute("onmouSEOver","");
document.getElementById(inputName+"Preview").setAttribute("onmouSEOut","");
}else{
var fileUrl = dataobj.rsp.fileUrl;
var realPath = dataobj.rsp.realPath;
var img = new Image();//构造JS的Image对象
img.src = fileUrl;//将本地图片赋给image对象
setTimeout(function(){
initPic(inputName,fileUrl,img.width,img.height);
document.getElementsByName(inputName+"editUrl")[0].value="false";
document.getElementsByName(inputName+"FileUrl")[0].value=realPath;
},500);
}
}
});
};
三、配置完成后,页面如下
选择对应的文件后,就会进行图片上传的动作,通过调用配置好的action调用到服务端
action:contentPath+"/file/fileup.do?actionType=upload&fileSize="+fileSize+"&ranNum="+Math.random(),
四、服务端进行处理,保存到临时文件下,等到发布商品时(项目中逻辑)在进行图片处理及路径保存入库
/*
* 上传
*/
public ActionForward performUpload(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response) {
try {
String jsonStr = FileUploadUtil.picUpload(request);
response.getWriter().println(jsonStr);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public static String picUpload(HttpServletRequest request) throws IOException {
String path = SystemManager.getValueByKey("file.temp.directory");
String date = DateUtil.getSysDateString();
// 获取文件大小
String fileSize = request.getParameter("fileSize");
// 存相对路径
String filePath = "";
if (!StringUtil.isEmpty(path)) {
if (path.endsWith("/")) {
filePath = path + "fileTemp/" + date;
} else {
filePath = path + "/" + "fileTemp/" + date;
}
} else {
filePath = request.getRealPath("/") + "fileTemp/" + date;
}
File uploadPath = new File(filePath);
// 检查文件夹是否存在 不存在 创建一个
if (!uploadPath.exists()) {
uploadPath.mkdirs();
}
// 文件最大容量
double size = 1.0;
if (!StringUtil.isEmpty(fileSize)) {
try {
size = Double.parseDouble(fileSize);
} catch (Exception e) {
// TODO: handle exception
}
}
int fileMaxSize = (int) (size * 1024 * 1024);
// 文件名
String fileName = null;
// 上传文件数
int fileCount = 0;
// 上传文件
MultipartRequest mulit = null;
try {
// 重命名策略
RandomFileRenamePolicy rfrp = new RandomFileRenamePolicy();
mulit = new MultipartRequest(request,filePath,fileMaxSize,"UTF-8",rfrp);
String userName = mulit.getParameter("userName");
System.out.println(userName);
} catch (Exception e) {
// TODO: handle exception
HashMap localHashMap1 = new HashMap();
HashMap localHashMap2 = new HashMap();
localHashMap2.put("errorMessage",e.getMessage());
localHashMap1.put("rsp",localHashMap2);
return JsonUtil.toString(localHashMap1);
}
Enumeration filesname = mulit.getFileNames();
while (filesname.hasMoreElements()) {
String name = (String) filesname.nextElement();
fileName = mulit.getFilesystemName(name);
String contentType = mulit.getContentType(name);
if (fileName != null) {
fileCount++;
}
System.out.println("文件名:" + fileName);
System.out.println("文件类型: " + contentType);
}
System.out.println("共上传" + fileCount + "个文件!");
String fileUrl = SystemManager.getValueByKey("file.temp.weburl");
if (StringUtil.isEmpty(fileUrl)) {
if (StringUtil.isEmpty(FileUtil.IMAGEROOT)) {
FileUtil.IMAGEROOT = ShopApplicationResource.shopResource
.getString("image.webroot");
}
String returnImage = FileUtil.IMAGEROOT;
fileUrl = returnImage;
//fileUrl = "http://" + request.getServerName();
//if (!"80".equals(request.getServerPort())) {
//fileUrl = fileUrl + ":" + request.getServerPort();
//}
fileUrl = fileUrl + request.getContextPath();
}
if (fileUrl.endsWith("/")) {
fileUrl = fileUrl + "fileTemp/" + date + "/" + fileName;
} else {
fileUrl = fileUrl + "/" + "fileTemp/" + date + "/" + fileName;
}
HashMap localHashMap1 = new HashMap();
HashMap localHashMap2 = new HashMap();
localHashMap2.put("fileUrl",fileUrl);
localHashMap2.put("realPath",filePath + "/" + fileName);
localHashMap2.put("errorMessage","");
localHashMap1.put("rsp",localHashMap2);
return JsonUtil.toString(localHashMap1);
}
利用ajaxupload.js插件(不需要form表单,利用ajax进行)上传图片工作就完成了,将ajaxupload.js部分代码粘贴
/**
* Easy styling and uploading
* @constructor
* @param button An element you want convert to
* upload button. Tested dimentions up to 500x500px
* @param {Object} options See defaults below.
*/
window.AjaxUpload = function(button,options){
this._settings = {
// Location of the server-side upload script
action: 'upload.PHP',
// File upload name
name: 'userfile',
// Additional data to send
data: {},
// Submit file as soon as it's selected
autoSubmit: true,
// The type of data that you're expecting back from the server.
// html and xml are detected automatically.
// Only useful when you are using json data as a response.
// Set to "json" in that case.
responseType: false,
// Class applied to button when mouse is hovered
hoverClass: 'hover',
// Class applied to button when AU is disabled
disabledClass: 'disabled',
// When user selects a file,useful with autoSubmit disabled
// You can return false to cancel upload
onChange: function(file,extension){
},
// Callback to fire before file is uploaded
// You can return false to cancel upload
onSubmit: function(file,
// Fired when file upload is completed
// WARNING! DO NOT USE "FALSE" STRING AS A RESPONSE!
onComplete: function(file,response){
}
};
// Merge the users options with our defaults
for (var i in options) {
if (options.hasOwnProperty(i)){
this._settings[i] = options[i];
}
}
// button isn't necessary a dom element
if (button.jquery){
// jQuery object was passed
button = button[0];
} else if (typeof button == "string") {
if (/^#.*/.test(button)){
// If jQuery user passes #elementId don't break it
button = button.slice(1);
}
button = document.getElementById(button);
}
if ( ! button || button.nodeType !== 1){
throw new Error("Please make sure that you're passing a valid element");
}
if ( button.nodeName.toUpperCase() == 'A'){
// disable link
addEvent(button,'click',function(e){
if (e && e.preventDefault){
e.preventDefault();
} else if (window.event){
window.event.returnValue = false;
}
});
}
// DOM element
this._button = button;
// DOM element
this._input = null;
// If disabled clicking on button won't do anything
this._disabled = false;
// if the button was disabled before refresh if will remain
// disabled in FireFox,let's fix it
this.enable();
this._rerouteClicks();
};
* Creates form,that will be submitted to iframe
* @param {Element} iframe Where to submit
* @return {Element} form
*/
_createForm: function(iframe){
var settings = this._settings;
// We can't use the following code in IE6
// var form = document.createElement('form');
// form.setAttribute('method','post');
// form.setAttribute('enctype','multipart/form-data');
// Because in this case file won't be attached to request
var form = toElement('<form method="post" enctype="multipart/form-data"></form>');
form.setAttribute('action',settings.action);
form.setAttribute('target',iframe.name);
form.style.display = 'none';
document.body.appendChild(form);
// Create hidden input element for each data key
for (var prop in settings.data) {
if (settings.data.hasOwnProperty(prop)){
var el = document.createElement("input");
el.setAttribute('type','hidden');
el.setAttribute('name',prop);
el.setAttribute('value',settings.data[prop]);
form.appendChild(el);
}
}
return form;
},