function getCustomSetting(setting){
var def = {
flash_url : uploadSwf,
upload_url: uploadUrl,
post_params: {targetForm:"form"},
file_size_limit : "10 MB",
file_types : "*.jpg",
file_types_description : "请选择图片文件",
button_image_url: myImage+"/plugins/swfupload/upload_btn.gif",
file_upload_limit : "0",
file_queue_limit : "1",
button_width: "216",
button_height: "23",
// custom_settings : {
// upload_target : "fsUploadProgress",
// cancelButtonId : "btnCancel"
// },
button_placeholder_id: "",
button_window_mode : SWFUpload.WINDOW_MODE.TRANSPARENT,
button_action : SWFUpload.BUTTON_ACTION.SELECT_FILES,
button_text: '',
button_text_style: ".theFont { font-size: 14; }",
button_text_left_padding: 5,
button_text_top_padding: 5,
button_cursor:SWFUpload.CURSOR.HAND,
// file_queued_handler : fileQueued,
// file_queue_error_handler : fileQueueError,
// file_dialog_complete_handler : fileDialogComplete,
// upload_start_handler : uploadStart,
// upload_progress_handler : uploadProgress,
// upload_error_handler : uploadError,
// upload_success_handler : customUploadSuccess,
// upload_complete_handler : uploadComplete,
// queue_complete_handler : queueComplete // Queue plugin event
// file_queued_handler : function(file){},
// file_queue_error_handler : function(file, errorCode, message){},
file_dialog_complete_handler : function(numFilesSelected, numFilesQueued){
this.startUpload();
},
// upload_start_handler : function(file){},
// upload_progress_handler : function(file, bytesLoaded, bytesTotal){},
// upload_error_handler : function(file, errorCode, message){},
upload_success_handler : customUploadSuccess,
upload_complete_handler : function(file,obj){},
queue_complete_handler : function(numFilesUploaded){}
};
$.extend(def,setting);
return def;
}
package com.xxx.basicspace.back.controller;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ExtendedModelMap;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
@Controller
public class FileUploadController {
private static Logger logger = Logger.getLogger(FileUploadController.class);
/**
* <p class="detail">图片传处理function</p>
*
* @author <a href="mailto:[email protected] ">邹平</a> 2012-4-10 下午01:31:19
* @param <b>这里参数</b>
* @return String 返回类型
* @throws
*/
@RequestMapping(value="/uc/uploadFileLogo.htm",method=RequestMethod.POST)
public void uploadFileLogo(HttpServletRequest request,HttpServletResponse response,String targetDom){
try {
response.setContentType("text/html; charset=GBK");
String fileName = "";
//项目发布路径
String path = request.getSession().getServletContext().getRealPath("")+File.separator;
//临时文件夹
String foler = File.separator+WokeFinal.HEAD_IMG;
//得到图片临时存放路径
File pfile = new File(path+foler);
if(!pfile.exists()){
pfile.mkdirs();
}
if(request instanceof MultipartHttpServletRequest){
//取得文件流
MultipartHttpServletRequest mrequest = (MultipartHttpServletRequest) request;
Map<String, MultipartFile> fileMap = mrequest.getFileMap();
Iterator<String> fileNames = mrequest.getFileNames();
while (fileNames.hasNext()) {
String inpuFileName = (String) fileNames.next();
CommonsMultipartFile file = (CommonsMultipartFile) fileMap.get(inpuFileName);
String fileByte = file.getFileItem().getName();
fileName = createFileName(fileByte);
try {
byte [] ss = file.getBytes();
FileOutputStream out = new FileOutputStream(path+foler+File.separator+fileName);
//需要优化
out.write(ss);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
response.getWriter().write("{'targetDom':'"+targetDom+"','fileName':'"+fileName+"'}");
}else{
response.getWriter().write("false");
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* <p class="detail">百度ueditor编辑器上传</p>
* @author <a href="mailto:[email protected] ">罗伟俊</a> 2013-1-22 下午6:19:04
* @param request
* @param response
* @param targetDom
* @param model
* @return
*/
@RequestMapping(value="/upload/baiduUploadFile.htm",method=RequestMethod.POST)
@ResponseBody
public String baiduUploadFile(HttpServletRequest request,HttpServletResponse response,String targetDom){
response.setContentType("text/html; charset=GBK");
String fileName = "";
Map<String,Object> resultMap = new HashMap<String, Object>();
//项目发布路径
String path = WokeFinal.realPath+"/";
//临时文件夹
String foler = "/"+WokeContext.getSystemProperties().getProperty("uploadColorful");
//得到图片临时存放路径
File saveDir = new File(path+foler+File.separator);
if(!saveDir.exists()){
saveDir.mkdirs();
}
if(request instanceof MultipartHttpServletRequest){
//取得文件流
MultipartHttpServletRequest mrequest = (MultipartHttpServletRequest) request;
Map<String, MultipartFile> fileMap = mrequest.getFileMap();
Iterator<String> fileNames = mrequest.getFileNames();
while (fileNames.hasNext()) {
String inpuFileName = (String) fileNames.next();
CommonsMultipartFile file = (CommonsMultipartFile) fileMap.get(inpuFileName);
String fileByte = file.getFileItem().getName();
fileName = createFileName(fileByte);
try {
ImgUtil.getNew().upload(file.getInputStream(), path+foler+File.separator+fileName, -1, -1, false, null,null, 1, 1, -1);
} catch (Exception e) {
logger.error("",e);
}
}
String url = foler+"/"+fileName;
resultMap.put("url", url);
resultMap.put("title", request.getParameter("pictitle"));
resultMap.put("state", "SUCCESS");
}else{
resultMap.put("url", "");
resultMap.put("title", "");
resultMap.put("state", "保存失败");
}
return JSONObject.fromObject(resultMap).toString();//{ "url":"图片地址", "title":"图片描述", "state":"上传状态" }
}
/**
* <p class="detail">图片传处理function</p>
*
* @author <a href="mailto:[email protected] ">邹平</a> 2012-4-10 下午01:31:19
* @param <b>这里参数</b>
* @return String 返回类型
* @throws
*/
@SuppressWarnings("unchecked")
@RequestMapping(value="/upload/uploadFile.htm",method=RequestMethod.POST)
public void uploadFile(HttpServletRequest request,HttpServletResponse response,String targetDom,ExtendedModelMap model){
try {
response.setContentType("text/html; charset=GBK");
String filePath="",fileName = "";
//项目发布路径
String dir = WokeFinal.realPath+File.separator;
//临时文件夹
String foler = File.separator+WokeFinal.TMEP_FILE;
//按月创建的临时文件夹
String tempFoler = DateUtil.getString("yyyyMM");
//得到图片临时存放路径
File pfile = new File(dir+foler+File.separator+tempFoler);
if(!pfile.exists()){
pfile.mkdirs();
}
if(request instanceof MultipartHttpServletRequest){
//取得文件流
MultipartHttpServletRequest mrequest = (MultipartHttpServletRequest) request;
Map<String, MultipartFile> fileMap = mrequest.getFileMap();
Iterator<String> fileNames = mrequest.getFileNames();
while (fileNames.hasNext()) {
String inpuFileName = (String) fileNames.next();
CommonsMultipartFile file = (CommonsMultipartFile) fileMap.get(inpuFileName);
String fileByte = file.getFileItem().getName();
//图片格式验证
fileName = createFileName(fileByte);
filePath = foler+File.separator+tempFoler+File.separator+fileName;
try {
byte [] ss = file.getBytes();
FileOutputStream out = new FileOutputStream(dir+filePath);
//需要优化
out.write(ss);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
filePath = filePath.replace("\\", "/");
Map<String,Object> map = new HashMap<String, Object>();
map.putAll(request.getParameterMap());
map.put("targetDom", targetDom);
map.put("filePath", filePath);
map.put("fileName", fileName);
JSONObject jsonObj = JSONObject.fromObject(map);
response.getWriter().write(jsonObj.toString());
}else{
logger.debug("文件上传请求类型错误!>>>>>>>>>>>>>>>");
response.getWriter().write("false");
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
*
* <p class="detail">图片传处理function</p>
*
* @author <a href="mailto:[email protected] ">邹平</a> 2012-4-10 下午01:31:19
* @param <b>这里参数</b>
* @return String 返回类型
* @throws
*/
@RequestMapping(value="/uc/uploadColorful.htm",method=RequestMethod.POST)
public String uploadColorful(HttpServletRequest request,
HttpServletResponse response,Model model){
response.setContentType("text/html; charset=GBK");
long start = System.currentTimeMillis();
String fileName = "";
//项目发布路径
String path = request.getSession().getServletContext().getRealPath("")+File.separator;
//临时文件夹
String foler = File.separator+WokeContext.getSystemProperties().getProperty("uploadColorful");
//得到图片临时存放路径
File pfile = new File(path+foler+File.separator);
if(!pfile.exists()){
pfile.mkdirs();
}
if(request instanceof MultipartHttpServletRequest){
//取得文件流
MultipartHttpServletRequest mrequest = (MultipartHttpServletRequest) request;
Map<String, MultipartFile> fileMap = mrequest.getFileMap();
Iterator<String> fileNames = mrequest.getFileNames();
//水印存放地址
String syPath = WokeContext.getSystemProperties().getProperty("shuiyinpath");
//生成水印目标文件夹
File syDir = new File(path+ File.separator + syPath);
if(!syDir.exists()){
model.addAttribute("error",1);
model.addAttribute("message","上传错误!");
return "texTemplate";
}
while (fileNames.hasNext()) {
String inpuFileName = (String) fileNames.next();
CommonsMultipartFile file = (CommonsMultipartFile) fileMap.get(inpuFileName);
String fileByte = file.getFileItem().getName();
fileName = createFileName(fileByte);
try {
ImgUtil.getNew().upload(file.getInputStream(), path+foler+File.separator+fileName, -1, -1, false, syDir,null, 1, 1, -1);
} catch (Exception e) {
logger.error("",e);
e.printStackTrace();
}
logger.debug("==fileName===="+fileName);
}
model.addAttribute("error",0);
model.addAttribute("url",fileName);
long end = System.currentTimeMillis();
logger.debug("end-start=="+(end-start));
}else{
model.addAttribute("error",1);
model.addAttribute("message","上传错误!");
}
return "texTemplate";
}
@RequestMapping(value="/getUploadFile")
public String getUploadFile(){
logger.debug("getUploadFile");
return "/upload/uploadfile";
}
private String createFileName(String fileName){
String postfix = fileName.substring(fileName.length()-4, fileName.length());
return StringUtil.uuid()+postfix;
}
/**
*
* Description: 验证上传文件格式 暂定为.jpg
*/
private boolean checkImageType(String fileName){
boolean flag = false;
if(fileName.endsWith(".jpg") || fileName.endsWith(".JPG")){
flag = true;
}
return flag;
}
/**
*
* <p class="detail">上传有水印的主图片</p>
*
* @author <a href="mailto:[email protected] ">邹平</a> 2012-4-10 下午01:31:19
* @param <b>这里参数</b>
* @return String 返回类型
* @throws
*/
@RequestMapping(value="/uploadAddSy",method=RequestMethod.POST)
public void uploadAddSy(HttpServletRequest request,
HttpServletResponse response){
try {
long start = System.currentTimeMillis();
response.setContentType("text/html; charset=GBK");
boolean upFlag = false;
String fileName = "";
//项目发布路径
String path = request.getSession().getServletContext().getRealPath("")+File.separator;
logger.debug("项目的发布路径:"+path);
//临时文件夹
String foler = File.separator+WokeContext.getSystemProperties().getProperty(WokeFinal.TMEP_FILE);
//按月创建的临时文件夹
String tempFoler = DateUtil.getString("yyyyMM");
//得到图片临时存放路径
File pfile = new File(path+foler+File.separator+tempFoler);
if(!pfile.exists()){
pfile.mkdirs();
}
//水印存放地址
String syPath = WokeContext.getSystemProperties().getProperty("shuiyinpath");
//生成水印目标文件夹
File syDir = new File(path+ File.separator + syPath);
if(!syDir.exists()){
logger.debug("水印文件夹不存在!>>>>>>>>>>>>>>>");
}
if(request instanceof MultipartHttpServletRequest){
//取得文件流
MultipartHttpServletRequest mrequest = (MultipartHttpServletRequest) request;
Map<String, MultipartFile> fileMap = mrequest.getFileMap();
Iterator<String> fileNames = mrequest.getFileNames();
while (fileNames.hasNext()) {
String inpuFileName = (String) fileNames.next();
CommonsMultipartFile file = (CommonsMultipartFile) fileMap.get(inpuFileName);
String fileByte = file.getFileItem().getName();
//图片格式验证
if(upFlag==checkImageType(fileByte)){
return ;
}else{
upFlag = checkImageType(fileByte);
}
//生成一个新图片名
fileName = createFileName(fileByte);
try {
ImgUtil.getNew().upload(file.getInputStream(), pfile+File.separator+fileName, -1, -1, false, syDir,null, 1, 1, -1);
} catch (Exception e) {
logger.error("图片上传失败!", e);
}
logger.debug("==fileName===="+fileName);
}
if(!upFlag){
response.getWriter().write("false");
}else{
logger.debug(tempFoler+"_"+fileName);
response.getWriter().write(tempFoler+"_"+fileName);
}
long end = System.currentTimeMillis();
logger.debug("图片上传共耗时>>>>>>>>>>>>>>>>>"+(end-start));
}else{
logger.debug("文件上传请求类型错误!>>>>>>>>>>>>>>>");
response.getWriter().write("false");
}
} catch (IOException e) {
e.printStackTrace();
}
}
@RequestMapping(value="/uploadFile",method=RequestMethod.POST)
public void uploadFile(HttpServletRequest request,
HttpServletResponse response){
try {
long start = System.currentTimeMillis();
response.setContentType("text/html; charset=GBK");
boolean upFlag = false;
String fileName = "";
String message = "对不起,文件上传失败了!请检查你上传的文件格式!";
//项目发布路径
String path = request.getSession().getServletContext().getRealPath("")+File.separator;
logger.debug("项目的发布路径:"+path);
//临时文件夹
String foler = File.separator+WokeContext.getSystemProperties().getProperty(WokeFinal.TMEP_FILE);
//按月创建的临时文件夹
String tempFoler = DateUtil.getString("yyyyMM");
//得到图片临时存放路径
File pfile = new File(path+foler+File.separator+tempFoler);
if(!pfile.exists()){
pfile.mkdirs();
}
if(request instanceof MultipartHttpServletRequest){
//取得文件流
MultipartHttpServletRequest mrequest = (MultipartHttpServletRequest) request;
Map fileMap = mrequest.getFileMap();
Iterator<String> fileNames = mrequest.getFileNames();
while (fileNames.hasNext()) {
String inpuFileName = (String) fileNames.next();
CommonsMultipartFile file = (CommonsMultipartFile) fileMap.get(inpuFileName);
String fileByte = file.getFileItem().getName();
//图片格式验证
if(upFlag==checkImageType(fileByte)){
return ;
}else{
upFlag = checkImageType(fileByte);
}
fileName = createFileName(fileByte);
try {
byte [] ss = file.getBytes();
FileOutputStream out = new FileOutputStream(path+foler+File.separator+tempFoler+File.separator+fileName);
//需要优化
out.write(ss);
out.flush();
out.close();
message = "图片上传成功!";
} catch (Exception e) {
e.printStackTrace();
}
logger.debug("==fileName===="+fileName);
}
if(!upFlag){
response.getWriter().write("false");
}else{
logger.debug(tempFoler+"_"+fileName);
response.getWriter().write(tempFoler+"_"+fileName);
}
long end = System.currentTimeMillis();
logger.debug("end-start=="+(end-start));
}else{
logger.debug("文件上传请求类型错误!>>>>>>>>>>>>>>>");
response.getWriter().write("false");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
//上传成功
function customUploadSuccess(file, serverData) {
var progress = false;
if(typeof FileProgress != "undefined"){
var progress = new FileProgress(file, this.customSettings.progressTarget);
}
try {
eval("var serverData = "+serverData+";");
if(progress){
progress.setComplete();
progress.setStatus("上传完成..");
}
var oldSrc = "";
if(serverData.targetDom && serverData.filePath){
oldSrc = $(serverData.targetDom).attr("src");
$(serverData.targetDom).attr("src",myPath+serverData.filePath);
}
if(serverData.targetForm && serverData.targetForm[0] && serverData.inputValue[0] && serverData.filePath && serverData.fileName){
var $form = $(serverData.targetForm[0]);
var $oldImgs = $form.find("#oldImgs");
var $hiddenHtml = $("<input name='"+serverData.inputValue[0]+"' value='"+serverData.fileName+"' type='hidden' />");
var $hiddenAlias = "";
var isHiddenAlias = false;
if(serverData.name && serverData.name[0]){//创建一个name 的隐藏表单
$hiddenAlias = $("<input name='"+serverData.name[0]+"' value='"+serverData.fileName+"' type='hidden' />");
isHiddenAlias = true;
}
if(serverData.domClass){//添加class,在删除的时候级联删除隐藏表单
$hiddenHtml.addClass(serverData.domClass[0]);
if(isHiddenAlias)$hiddenAlias.addClass(serverData.domClass[0]);
}
//老图片
if($oldImgs.length == 0){
$form.prepend("<input id='oldImgs' name='oldImgs' value='"+oldSrc+"' type='hidden'/>");
}else{
oldSrc = $oldImgs.val() + ","+oldSrc;
$oldImgs.val(oldSrc);
}
var $inputHidden = $form.find("input[name='"+serverData.inputValue[0]+"']");
$inputHidden.remove();
$hiddenHtml.prependTo($form);
if(isHiddenAlias){
$form.find("input[name='"+serverData.name[0]+"']").remove();
$hiddenAlias.prependTo($form);
}
if(serverData.group && serverData.group[0]){
var groupStr = serverData.group[0].replace("[","\\[").replace("]","\\]");
$hiddenHtml.attr("uploadgroup",groupStr);
var $group = $form.find("input[uploadgroup='"+groupStr+"']");
if($("#uploadGroup_"+groupStr).length == 0){
var $groupHtm = $("<input name='"+serverData.group[0]+"' id='uploadGroup_"+serverData.group[0]+"' value='"+serverData.fileName+"' type='hidden' />");
$form.prepend($groupHtm);
if(serverData.domClass){$groupHtm.addClass(serverData.domClass[0]);}
}else{
var groupHiddenValue = "";
for(var i=0;i<$group.length;i++){
if(i > 0){groupHiddenValue+=",";};
groupHiddenValue += $group.eq(i).val();
}
$("#uploadGroup_"+groupStr).val(groupHiddenValue);
}
}
}
} catch (ex) {
this.debug(ex);
}
if(progress){
progress.toggleCancel(false);
}
}