文件上传下载UploadUtil

来源:互联网 发布:windows怎么开ssh 编辑:程序博客网 时间:2024/06/05 14:39


UploadUtil代码


package import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.util.Arrays;import org.slf4j.Logger;import org.slf4j.LoggerFactory;public class UploadUtil {private static final String CMD_SELECT_FREE_SPACE = "df -P -hT";private final static Logger LOG = LoggerFactory.getLogger(UploadUtil.class);/** * 查询当前路径所在磁盘的剩余空间 *  * @param path * @return 剩余空间字节数 */public static double getFreeSpaceByPath(String path) {double freeHD = 0;BufferedReader reader = null;try {Runtime rt = Runtime.getRuntime();Process p = rt.exec(CMD_SELECT_FREE_SPACE + " " + path);reader = new BufferedReader(new InputStreamReader(p.getInputStream()));String str = null;String[] strArray = null;while ((str = reader.readLine()) != null) {int m = 0;strArray = str.split(" ");LOG.info("df -P -hT result:" + Arrays.toString(strArray) + ";m:" + m);for (String tmp : strArray) {if (tmp.trim().length() == 0)continue;if (tmp.indexOf("T") != -1) {if (m == 4) {if (!tmp.equals("none") && !tmp.equals("0"))freeHD = Double.parseDouble(tmp.substring(0, tmp.length() - 1)) * 1024 * 1024 * 1024 * 1024;}}else if (tmp.indexOf("G") != -1) {if (m == 4) {if (!tmp.equals("none") && !tmp.equals("0"))freeHD = Double.parseDouble(tmp.substring(0, tmp.length() - 1)) * 1024 * 1024 * 1024;}}else if (tmp.indexOf("M") != -1) {if (m == 4) {if (!tmp.equals("none") && !tmp.equals("0"))freeHD = Double.parseDouble(tmp.substring(0, tmp.length() - 1)) * 1024 * 1024;}}m++;}}} catch (Exception e) {LOG.error("Get disk free space error. path=" + path, e);} finally {try {if (reader != null) {reader.close();}} catch (IOException e) {LOG.error("Close reader error.", e);}}LOG.info("The path=" + path + ",and the disk have free space is " + freeHD);return freeHD;}}


uploadController


package import java.awt.image.BufferedImage;import java.io.*;import java.text.SimpleDateFormat;import java.util.ArrayList;import java.util.Date;import java.util.List;import java.util.Map;import java.util.Properties;import java.util.UUID;import javax.imageio.ImageIO;import javax.servlet.ServletInputStream;import javax.servlet.ServletOutputStream;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import com.lixin.secure.user.common.Constants;import org.apache.commons.io.IOUtils;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.util.FileCopyUtils;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.ResponseBody;import org.springframework.web.multipart.MultipartFile;import org.springframework.web.multipart.MultipartHttpServletRequest;import com.alibaba.druid.util.StringUtils;@RequestMapping("upload")@Controllerpublic class UploadController {private final static Logger LOG = LoggerFactory.getLogger(UploadController.class);/** * 文件上传根路径,当前磁盘满时,支持自动切换到挂载的其他盘 */private static List rootpaths = new ArrayList();/** * 文件上传格式 */private static List fileTypes = new ArrayList();/** * 文件上传大小限制,单位:字节 */private static Long limitFileSize = 0L;/** * 磁盘剩余空间阈值,单位:字节 */private static double limitFreeSpace = 0L;static {Properties properties = new Properties();FileInputStream fis = null;try {// 初始化文件上传参数:文件保存路径,文件格式,文件大小fis = new FileInputStream(StringUtils.class.getClassLoader().getResource("/").getPath() + "fileconfig.properties");properties.load(fis);String[] file_root_path = properties.getProperty("file_root_path").split(";");for (String path : file_root_path) {if (!path.endsWith(File.separator)) {rootpaths.add(path + File.separator);} else {rootpaths.add(path);}}String[] file_types = properties.getProperty("file_types").split(";");for (String type : file_types) {fileTypes.add(type);}limitFileSize = Long.valueOf(properties.getProperty("file_size_limit")) * 1024 * 1024;limitFreeSpace = Double.valueOf(properties.getProperty("upload_disk_threshold")) * 1024 * 1024 * 1024;} catch (FileNotFoundException e) {LOG.error("the file config not found.", e);} catch (IOException e) {LOG.error("load file config error.", e);} finally {try {if (fis != null) {fis.close();}} catch (IOException e) {LOG.error("load file config error.", e);}}}/** * 上传文件或删除服务端文件时检测当前用户是否有权限可操作 *  * @param request * @param response * @param filePath * @return */@RequestMapping(value = "/checkPermission", method = { RequestMethod.POST })@ResponseBodypublic ActionResult checkPermission(@RequestParam(required = true, defaultValue = "0") Long parentId,@RequestParam(required = true, defaultValue = "") Integer type) {return checkAuth(parentId, type);}return result;}/** * 检查上传文件类型 *  * @param fullFileName *            文件全名称 * @return */private boolean checkFileType(String fullFileName) {String type = fullFileName.substring(fullFileName.lastIndexOf(".") + 1, fullFileName.length());if (fileTypes.contains(type.toLowerCase())) {return true;}LOG.error("Cannot support the file type,name=" + fullFileName);return false;}/** * 检查上传文件大小 *  * @param fileSize *            文件字节大小 * @return */private boolean checkFileSize(Long fileSize) {if (limitFileSize < fileSize) {LOG.error("The file is too big,size=" + fileSize);return false;}return true;}/** * 获取要上传的磁盘路径 *  * @return */private String getUploadPath() {if (rootpaths == null || rootpaths.isEmpty()) {return "";}for (String path : rootpaths) {if (!System.getProperty("os.name").equalsIgnoreCase("linux")) {return path;}double freespace = UploadUtil.getFreeSpaceByPath(path);if (freespace > limitFreeSpace) {return path;}LOG.info("The disk free space have not enough[path=" + path + "],switch next path");}return "";}/** * 获取已经上传的文件的路径 *  * @return */private String getUploadFilePath(String relativePath) {if (rootpaths == null || rootpaths.isEmpty()) {return relativePath;}for (String path : rootpaths) {File file = new File(path + relativePath);if (file.exists()) {return path + relativePath;}LOG.warn("The file path is not exists[filepath=" + path + relativePath + "],switch next path");}return "";}// SWFUpload单击上传以后的响应函数@RequestMapping(value = "/upload", method = { RequestMethod.POST })public @ResponseBody String upload(HttpServletRequest request, HttpServletResponse response) throws Exception {// 多文件上传的时候,封装的请求参数MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;// 获取前台传递过来的文件参数Map fileMap = multipartRequest.getFileMap();// 文件名的格式化——年月String ymd = new SimpleDateFormat("yyyyMM").format(new Date()) + File.separator+ new SimpleDateFormat("dd").format(new Date()) + File.separator;String uploadPath = getUploadPath();if (uploadPath == null || uploadPath.isEmpty()) {return "nofreespace";}String ctxPath = uploadPath + ymd;// 创建文件夹File file = new File(ctxPath);if (!file.exists()) {file.mkdirs();}String fileName = null;String path = null;String newFileName = null;for (Map.Entry entity : fileMap.entrySet()) {MultipartFile mf = entity.getValue();if (!checkFileSize(mf.getSize()) || !checkFileType(mf.getOriginalFilename())) {return "notsupport";}}for (Map.Entry entity : fileMap.entrySet()) {MultipartFile mf = entity.getValue();fileName = mf.getOriginalFilename();String strEnc = fileName.substring(0, fileName.lastIndexOf('.'));// 加密字符串,返回String的密文String uuid = UUID.randomUUID().toString().replaceAll("\\-", "");// 返回一个随机UUID。String suffix = fileName.indexOf(".") != -1? fileName.substring(fileName.lastIndexOf("."), fileName.length()) : null;newFileName = strEnc + "-" + uuid + (suffix != null ? suffix : "");// 构成新文件名。File uploadFile = new File(ctxPath + newFileName);try {FileCopyUtils.copy(mf.getBytes(), uploadFile);path = ymd + File.separator + newFileName;} catch (IOException e) {LOG.error("upload file error.", e);}}return path;}/** * 验证文件类型 * @param id 文件id * @return ActionResult statusCode为1 表示图片 否则为其他文件 */@RequestMapping("/validateFileType")@ResponseBodypublic ActionResult validateFileType(Long id){ActionResult actionResult = new ActionResult();CaseFileEntity fileRecord = uploadFileService.selectByPrimaryKey(id);String fileType = fileRecord.getOriginalFileName().substring(fileRecord.getOriginalFileName().lastIndexOf(".") + 1, fileRecord.getOriginalFileName().length());//判断是否为图片if (Constants.IMG_TYPE.IMGTYPES.contains(fileType)) {actionResult.setStatusCode(1);//1表示图片return actionResult;}        //其他类型actionResult.setStatusCode(2);return actionResult;}/*** * 图片预览页面 * @param request * @param imgSrc * @return */@RequestMapping("/imgView")public String imgView(HttpServletRequest request,Long id){        request.setAttribute("id", id);return "upload/imgview";}/*** * 获取图片流 * @param id * @return */    @RequestMapping("/getImgPath")@ResponseBodypublic void getImgPath(Long id,HttpServletResponse response){CaseFileEntity fileRecord = uploadFileService.selectByPrimaryKey(id);String fileType = fileRecord.getOriginalFileName().substring(fileRecord.getOriginalFileName().lastIndexOf(".") + 1, fileRecord.getOriginalFileName().length());String path = getUploadFilePath(fileRecord.getFilePath() + fileRecord.getFileName());ServletOutputStream sos =null;FileInputStream inputStream=null;ByteArrayInputStream is=null;try {sos= response.getOutputStream();inputStream = new FileInputStream(path);//转换为字节byte[] bytes = IOUtils.toByteArray(inputStream);is = new ByteArrayInputStream(bytes);BufferedImage bufferedImage = ImageIO.read(is);//写出图片流 图片类型为fileTypeImageIO.write(bufferedImage, fileType, sos);} catch (Exception e) {e.printStackTrace();}finally {if(is!=null){try {is.close();} catch (IOException e) {e.printStackTrace();}}if(inputStream!=null) {try {inputStream.close();} catch (IOException e) {e.printStackTrace();}}if(sos!=null) {try {sos.close();} catch (IOException e) {e.printStackTrace();}}}}/** * 从服务端下载文件 *  * @param request * @param response * @return */@RequestMapping(value = "/download")@ResponseBodypublic void download(@RequestParam(required = true, defaultValue = "") Long id, HttpServletResponse response)throws IOException {InputStream in = null;OutputStream out = null;// 根据当前附件id查询附件信息CaseFileEntity fileRecord = uploadFileService.selectByPrimaryKey(id);String path = getUploadFilePath(fileRecord.getFilePath() + File.separator + fileRecord.getFileName());File file = new File(path);// 将下载文件名变成中文选择String fileName = new String(fileRecord.getOriginalFileName().getBytes("UTF-8"), "iso-8859-1");// 为了解决中文名称乱码问题response.setCharacterEncoding("UTF-8");response.setContentType("multipart/form-data");response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);try {in = new FileInputStream(file);out = response.getOutputStream();byte[] b = new byte[2048];int length;while ((length = in.read(b)) > 0) {out.write(b, 0, length);}out.flush();} catch (Exception e) {LOG.error("Download error.", e);} finally {if (in != null) {try {in.close();} catch (Exception e) {LOG.error("Close inputstream error.", e);}}if (out != null) {try {out.close();} catch (Exception e) {LOG.error("Close outputstream error.", e);}}}}/** * 删除附件 *  * @param request * @param response * @param filePath * @return */@RequestMapping(value = "/removefile", method = { RequestMethod.POST })@ResponseBodypublic ActionResult removefile(HttpServletRequest request, HttpServletResponse response,@RequestParam(required = false, defaultValue = "0") Long id,@RequestParam(required = false, defaultValue = "") String filePath) {ActionResult result = new ActionResult();try {if (id > 0) {CaseFileEntity fileRecord = uploadFileService.selectByPrimaryKey(id);uploadFileService.deleteExsistFile(id);filePath = fileRecord.getFilePath() + File.separator + fileRecord.getFileName();}File file = new File(getUploadFilePath(filePath));if (file.exists()) {file.delete();}result.setMessage("删除文件成功。");result.setStatusCode(1);} catch (Exception e) {result.setMessage(e.getMessage());result.setStatusCode(ErrorCode.ERROR);LOG.error("remove file error,file=" + filePath, e);}return result;}/** * 根据上传文件路径和所属单据ID删除附件 *  * @param request * @param response * @param filePath * @return */@RequestMapping(value = "/removefileByPath", method = { RequestMethod.POST })@ResponseBodypublic ActionResult removefileByPath(HttpServletRequest request, HttpServletResponse response,@RequestParam(required = false, defaultValue = "") Long parentId,@RequestParam(required = false, defaultValue = "") String filePath) {ActionResult result = new ActionResult();try {String[] path = filePath.split("\\" + File.separator);uploadFileService.deleteByPathAndParentId(path, parentId);File file = new File(getUploadFilePath(filePath));if (file.exists()) {file.delete();}result.setMessage("删除文件成功。");result.setStatusCode(1);} catch (Exception e) {result.setMessage(e.getMessage());result.setStatusCode(ErrorCode.ERROR);LOG.error("remove file error,file=" + filePath, e);}return result;}// 根据caseId列出指定的附件信息@RequestMapping(value = "/files.json")@ResponseBodypublic List files(@RequestParam Long caseId, @RequestParam Integer type) {List fileNameAndPath = uploadFileService.files(caseId, type);return fileNameAndPath;}// 将附件信息持久化到数据库@RequestMapping(value = "/savefiles.json")@ResponseBodypublic ActionResult saveFiles(@RequestParam Long caseId, @RequestParam("filenamelist[]") String[] filenamelist,@RequestParam Integer type) {ActionResult result = new ActionResult();try {uploadFileService.saveUploadFile(caseId, filenamelist, type);result.setMessage("上传文件成功。");result.setStatusCode(1);} catch (Exception e) {result.setMessage(e.getMessage());result.setStatusCode(ErrorCode.ERROR);LOG.error("save upload file error,file=" + filenamelist, e);}return result;}}