文件controller

https://github.com/hawkroc/SpringMVC-Hibernate-ehcache/blob/master/src/main/java/sy/controller/FileController.java

packagesy.controller;

importjava.io.File;

importjava.io.IOException;

importjava.text.SimpleDateFormat;

importjava.util.ArrayList;

importjava.util.Arrays;

importjava.util.Collections;

importjava.util.Date;

importjava.util.HashMap;

importjava.util.Hashtable;

importjava.util.List;

importjava.util.Map;

importjava.util.UUID;

importjavax.servlet.http.HttpServletRequest;

importjavax.servlet.http.HttpServletResponse;

importjavax.servlet.http.HttpSession;

importorg.apache.commons.fileupload.FileItem;

importorg.apache.commons.fileupload.FileItemFactory;

importorg.apache.commons.fileupload.FileUploadException;

importorg.apache.commons.fileupload.disk.DiskFileItemFactory;

importorg.apache.commons.fileupload.servlet.ServletFileUpload;

importorg.springframework.stereotype.Controller;

importorg.springframework.web.bind.annotation.RequestMapping;

importorg.springframework.web.bind.annotation.ResponseBody;

importsy.comparator.NameComparator;

importsy.comparator.SizeComparator;

importsy.comparator.TypeComparator;

importsy.util.ConfigUtil;

/**

*文件控制器

*

*@author孙宇

*

*/

@Controller

@RequestMapping("/fileController")

publicclassFileControllerextendsBaseController{

/**

*浏览器服务器附件

*

*@paramresponse

*@paramrequest

*@paramsession

*@return

*/

@RequestMapping("/fileManage")

@ResponseBody

publicMap<String,Object>fileManage(HttpServletResponseresponse,HttpServletRequestrequest,HttpSessionsession){

Map<String,Object>m=newHashMap<String,Object>();

//根目录路径,可以指定绝对路径,比如/var/www/attached/

StringrootPath=session.getServletContext().getRealPath("/")+"attached/";

//根目录URL,可以指定绝对路径,比如http://www.yoursite.com/attached/

StringrootUrl=request.getContextPath()+"/attached/";

//图片扩展名

String[]fileTypes=newString[]{"gif","jpg","jpeg","png","bmp"};

StringdirName=request.getParameter("dir");

if(dirName!=null){

if(!Arrays.<String>asList(newString[]{"image","flash","media","file"}).contains(dirName)){

//out.println("InvalidDirectoryname.");

//return;

try{

response.getWriter().write("无效的目录名称!");

}catch(IOExceptione){

e.printStackTrace();

}

returnm;

}

rootPath+=dirName+"/";

rootUrl+=dirName+"/";

FilesaveDirFile=newFile(rootPath);

if(!saveDirFile.exists()){

saveDirFile.mkdirs();

}

}

//根据path参数,设置各路径和URL

Stringpath=request.getParameter("path")!=null?request.getParameter("path"):"";

StringcurrentPath=rootPath+path;

StringcurrentUrl=rootUrl+path;

StringcurrentDirPath=path;

StringmoveupDirPath="";

if(!"".equals(path)){

Stringstr=currentDirPath.substring(0,currentDirPath.length()-1);

moveupDirPath=str.lastIndexOf("/")>=0?str.substring(0,str.lastIndexOf("/")+1):"";

}

//排序形式,nameorsizeortype

Stringorder=request.getParameter("order")!=null?request.getParameter("order").toLowerCase():"name";

//不允许使用..移动到上一级目录

if(path.indexOf("..")>=0){

//out.println("Accessisnotallowed.");

//return;

try{

response.getWriter().write("不允许访问!");

}catch(IOExceptione){

e.printStackTrace();

}

returnm;

}

//最后一个字符不是/

if(!"".equals(path)&&!path.endsWith("/")){

//out.println("Parameterisnotvalid.");

//return;

try{

response.getWriter().write("参数无效!");

}catch(IOExceptione){

e.printStackTrace();

}

returnm;

}

//目录不存在或不是目录

FilecurrentPathFile=newFile(currentPath);

if(!currentPathFile.isDirectory()){

//out.println("Directorydoesnotexist.");

//return;

try{

response.getWriter().write("目录不存在!");

}catch(IOExceptione){

e.printStackTrace();

}

returnm;

}

//遍历目录取的文件信息

List<Hashtable<String,Object>>fileList=newArrayList<Hashtable<String,Object>>();

if(currentPathFile.listFiles()!=null){

for(Filefile:currentPathFile.listFiles()){

Hashtable<String,Object>hash=newHashtable<String,Object>();

StringfileName=file.getName();

if(file.isDirectory()){

hash.put("is_dir",true);

hash.put("has_file",(file.listFiles()!=null));

hash.put("filesize",0L);

hash.put("is_photo",false);

hash.put("filetype","");

}elseif(file.isFile()){

StringfileExt=fileName.substring(fileName.lastIndexOf(".")+1).toLowerCase();

hash.put("is_dir",false);

hash.put("has_file",false);

hash.put("filesize",file.length());

hash.put("is_photo",Arrays.<String>asList(fileTypes).contains(fileExt));

hash.put("filetype",fileExt);

}

hash.put("filename",fileName);

hash.put("datetime",newSimpleDateFormat("yyyy-MM-ddHH:mm:ss").format(file.lastModified()));

fileList.add(hash);

}

}

if("size".equals(order)){

Collections.sort(fileList,newSizeComparator());

}elseif("type".equals(order)){

Collections.sort(fileList,newTypeComparator());

}else{

Collections.sort(fileList,newNameComparator());

}

m.put("moveup_dir_path",moveupDirPath);

m.put("current_dir_path",currentDirPath);

m.put("current_url",currentUrl);

m.put("total_count",fileList.size());

m.put("file_list",fileList);

returnm;

}

/**

*

*@paramresponse

*@paramrequest

*@paramsession

*@return

*/

@RequestMapping("/upload")

@ResponseBody

publicMap<String,Object>upload(HttpServletResponseresponse,HttpServletRequestrequest,HttpSessionsession){

Map<String,Object>m=newHashMap<String,Object>();

m.put("error",1);

m.put("message","上传失败!");

//文件保存目录路径

StringsavePath=session.getServletContext().getRealPath("/")+"attached/";

//文件保存目录URL

StringsaveUrl=request.getContextPath()+"/attached/";

//定义允许上传的文件扩展名

HashMap<String,String>extMap=newHashMap<String,String>();

extMap.put("image",ConfigUtil.get("image"));

extMap.put("flash",ConfigUtil.get("flash"));

extMap.put("media",ConfigUtil.get("media"));

extMap.put("file",ConfigUtil.get("file"));

longmaxSize=Long.parseLong(ConfigUtil.get("maxFileSize"));//允许上传最大文件大小(字节)

if(!ServletFileUpload.isMultipartContent(request)){

m.put("error",1);

m.put("message","请选择文件!");

returnm;

}

//检查目录

FileuploadDir=newFile(savePath);

if(!uploadDir.isDirectory()){

uploadDir.mkdirs();

}

//检查目录写权限

if(!uploadDir.canWrite()){

m.put("error",1);

m.put("message","上传目录没有写权限!");

returnm;

}

StringdirName=request.getParameter("dir");

if(dirName==null){

dirname="image";

}

if(!extMap.containsKey(dirName)){

m.put("error",1);

m.put("message","目录名不正确!");

returnm;

}

//创建文件夹

savePath+=dirName+"/";

saveUrl+=dirName+"/";

FilesaveDirFile=newFile(savePath);

if(!saveDirFile.exists()){

saveDirFile.mkdirs();

}

SimpleDateFormatyearDf=newSimpleDateFormat("yyyy");

SimpleDateFormatmonthDf=newSimpleDateFormat("MM");

SimpleDateFormatdateDf=newSimpleDateFormat("dd");

Datedate=newDate();

Stringymd=yearDf.format(date)+"/"+monthDf.format(date)+"/"+dateDf.format(date)+"/";

savePath+=ymd;

saveUrl+=ymd;

FiledirFile=newFile(savePath);

if(!dirFile.exists()){

dirFile.mkdirs();

}

if(ServletFileUpload.isMultipartContent(request)){//判断表单是否存在enctype="multipart/form-data"

FileItemFactoryfactory=newDiskFileItemFactory();

ServletFileUploadupload=newServletFileUpload(factory);

upload.setHeaderEncoding("UTF-8");

try{

List<FileItem>items=upload.parseRequest(request);

for(FileItemitem:items){

StringfileName=item.getName();

if(!item.isFormField()){

//检查文件大小

if(item.getSize()>maxSize){

m.put("error",1);

m.put("message","上传文件大小超过限制!(允许最大["+maxSize+"]字节,您上传了["+item.getSize()+"]字节)");

returnm;

}

//检查扩展名

StringfileExt=fileName.substring(fileName.lastIndexOf(".")+1).toLowerCase();

if(!Arrays.<String>asList(extMap.get(dirName).split(",")).contains(fileExt)){

m.put("error",1);

m.put("message","上传文件扩展名是不允许的扩展名。\n只允许"+extMap.get(dirName)+"格式!");

returnm;

}

StringnewFileName=UUID.randomUUID().toString()+"."+fileExt;

try{

FileuploadedFile=newFile(savePath,newFileName);

item.write(uploadedFile);

}catch(Exceptione){

m.put("error",1);

m.put("message","上传文件失败!");

returnm;

}

m.put("error",0);

m.put("url",saveUrl+newFileName);

}

}

}catch(FileUploadExceptione){

e.printStackTrace();

}

}

returnm;

}

}

StatusAPITrainingShopBlogAbout

©2016GitHub,Inc.TermsPrivacy

相关推荐