上传和下载文件常用工具类

这次分享只是为了有个更快捷的编程,希望大家能够提出好的建议

//	前台代码
请选择文件:
//后台代码\
@Controller
@RequestMapping("/controller")
public class FileControllor {
    //文件上传
    @RequestMapping(value="/upload",method= RequestMethod.POST)
    @ResponseBody
    public void upload(HttpServletRequest request,@RequestParam("file1") MultipartFile file1,@RequestParam("file2") MultipartFile file2) throws Exception {
   		 //上传单个文件到指定文件夹
        String path="/upload/123213/1/1/";
        Map stringStringMap = FileUtil.FileUpload(request, path,file1);
        //上传你多个文件到同个文件夹
        //String path ="/upload/"
        //文件不需要传,在request中会自动获取上传的文件 file1和file2只是为了看保存的地址
       // Map stringStringMap =  FileUtil.multiFileUpload(request,path);
        //产出的map包含上传的文件名和上传的地址   此处为或去file1的文件地址
        stringStringMap.get(file1.getOriginalFilename());
    }
//文件下载
    @RequestMapping(value="/download",method= RequestMethod.GET)
    @ResponseBody
    public  ResponseEntity download(HttpServletRequest request) throws Exception {
        String realPath="upload/123213/1/1/新建文本文档 (2)1567059199248.txt";
        ResponseEntity download = FileUtil.download(request,realPath);
        return download;
    }
}

接下来就是最重要的下载和上传的代码了,注意注意!!!

//这里就是工具类了哦

//设置处理编码为utf-8
 private static final String ENCODING = "utf-8";

        /**
         * 文件下载
         * @param request  请求
         * @param filePath  文件名例如"/upload/XXX.txt"
         */
        public static ResponseEntity download(HttpServletRequest request,String filePath) throws UnsupportedEncodingException, IOException {
            String realPath = request.getSession().getServletContext().getRealPath("/");
            filePath=realPath+filePath;
            String fileName = FilenameUtils.getName(filePath);
            return downloadAssist(filePath, fileName);
        }
        /**
         * 文件下载辅助
         * @param filePath 文件路径
         * @param fileName 文件名
         */
        private static ResponseEntity downloadAssist(String filePath, String fileName) throws UnsupportedEncodingException, IOException {
            File file = new File(filePath);
            if (!file.isFile() || !file.exists()) {
                throw new IllegalArgumentException("filePath 参数必须是真实存在的文件路径:" + filePath);
            }
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment", URLEncoder.encode(fileName, ENCODING));
            return new ResponseEntity(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
        }

        /**
         * 单个文件上传不同文件夹
         * basePath  文件夹路径  "/upload/123213/1/1/"
         * multipartFile 上传的文件
         * @return Map 返回上传文件的保存路径 以文件名做map的key;文件保存路径作为map的value
         */
        public static Map FileUpload(HttpServletRequest request, String basePath,MultipartFile multipartFile) throws IllegalStateException, IOException {
            File file = null;
            //创建文件夹
            String realPath = request.getSession().getServletContext().getRealPath("/");
            basePath = realPath + basePath;
            while (!(new File(basePath).isDirectory())) {
                new File(basePath).mkdirs();
            }
            //上传文件
            Map filePaths = new HashMap();
            String fileName = multipartFile.getOriginalFilename();
            if (StringUtils.isNotEmpty(fileName)) {
                file = new File(basePath + changeFilename2UUID(fileName));
                filePaths.put(fileName, file.getPath());
                multipartFile.transferTo(file);

            }
            return filePaths;
        }

        /**
         * 多文件上传到同一文件夹
         * @param request 当前上传的请求
         * @param basePath 保存文件的路径  "/upload/123213/1/1/"
         * @return Map 返回上传文件的保存路径 以文件名做map的key;文件保存路径作为map的value
         */
        public static Map multiFileUpload(HttpServletRequest request, String basePath) throws IllegalStateException, IOException {
            String realPath = request.getSession().getServletContext().getRealPath("/");
            basePath=realPath+basePath;
            while (!(new File(basePath).isDirectory())) {
                new File(basePath).mkdirs();
            }
            return multifileUploadAssist(request, basePath);
        }

    /**
     * 多文件上传辅助
     * @param request  当前上传的请求
     * @param basePath 保存文件的路径
     */
        private static Map multifileUploadAssist(HttpServletRequest request, String basePath) throws IOException {
            Map filePaths = new HashMap();
            File file = null;
            // 创建一个通用的多部分解析器
            CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
            // 判断 request 是否有文件上传,即多部分请求
            if (multipartResolver.isMultipart(request)) {
                // 转换成多部分request
                MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
                // get the parameter names of the MULTIPART files contained in this request
                Iterator iter = multiRequest.getFileNames();
                while (iter.hasNext()) {
                    // 取得上传文件
                    List multipartFiles = multiRequest.getFiles(iter.next());
                    for (MultipartFile multipartFile : multipartFiles) {
                        String fileName = multipartFile.getOriginalFilename();
                        if (StringUtils.isNotEmpty(fileName)) {
                            file = new File(basePath + changeFilename2UUID(fileName));
                            filePaths.put(fileName, file.getPath());
                            multipartFile.transferTo(file);
                        }
                    }
                }
            }
            return filePaths;
        }

        /**
         * 将文件名称转化为uuid,并保留扩展名
         * @param filename  文件名
         */
        public static String changeFilename2UUID(String filename) {
            String name = filename.substring(0, filename.lastIndexOf("."));
            return name+new Date().getTime() + "." + FilenameUtils.getExtension(filename);
        }

        /**
         * 删除文件
         * @param filePath 文件地址
         */
        public static void deleteFile(String filePath) {
            try {
                File file = new File(filePath);
                if (file.exists() && file.isFile()) {
                    file.delete();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
`

你可能感兴趣的:(上传和下载文件常用工具类)