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

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

//	前台代码
<form action="/controller/upload"  method="post" enctype="multipart/form-data" >
    <table>
        <tr>
            <td>请选择文件:</td>
            <td><input type="file" name="file2"></td>
            <td><input type="file" name="file1"></td>
        </tr>
    </table>
    <input type="submit" value="上传文件">
</form>
<button onclick="xiazai()">文件下载</button>
<script >
function xiazai() {
    window.location.href="<%=basePath%>controller/download"
}
</script>
//后台代码\
@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<String, String> stringStringMap = FileUtil.FileUpload(request, path,file1);
        //上传你多个文件到同个文件夹
        //String path ="/upload/"
        //文件不需要传,在request中会自动获取上传的文件 file1和file2只是为了看保存的地址
       // Map<String, String> stringStringMap =  FileUtil.multiFileUpload(request,path);
        //产出的map包含上传的文件名和上传的地址   此处为或去file1的文件地址
        stringStringMap.get(file1.getOriginalFilename());
    }
//文件下载
    @RequestMapping(value="/download",method= RequestMethod.GET)
    @ResponseBody
    public  ResponseEntity<byte[]> download(HttpServletRequest request) throws Exception {
        String realPath="upload/123213/1/1/新建文本文档 (2)1567059199248.txt";
        ResponseEntity<byte[]> 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<byte[]> 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<byte[]> 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<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
        }

        /**
         * 单个文件上传不同文件夹
         * basePath  文件夹路径  "/upload/123213/1/1/"
         * multipartFile 上传的文件
         * @return Map<String, String> 返回上传文件的保存路径 以文件名做map的key;文件保存路径作为map的value
         */
        public static Map<String, String> 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<String, String> filePaths = new HashMap<String, String>();
            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<String, String> 返回上传文件的保存路径 以文件名做map的key;文件保存路径作为map的value
         */
        public static Map<String, String> 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<String, String> multifileUploadAssist(HttpServletRequest request, String basePath) throws IOException {
            Map<String, String> filePaths = new HashMap<String, String>();
            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<String> iter = multiRequest.getFileNames();
                while (iter.hasNext()) {
                    // 取得上传文件
                    List<MultipartFile> 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();
            }
        }
`

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值