码迷,mamicode.com
首页 > Web开发 > 详细

图片-文件上传下载

时间:2018-11-13 20:32:29      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:上传下载   tput   content   img   byte   buffere   bsp   tee   trace   

上传文件

    /**
     * 上传文件
     * @return
     */
    @RequestMapping(value = "/uploadfile", method = RequestMethod.POST)
    public Result uploadImage(@RequestParam("file") MultipartFile file) {
        try {
            if (file.isEmpty()) {
                return Result.error("文件为空");
            }
            // 获取文件名
            String fileName = System.currentTimeMillis()+ file.getOriginalFilename();
            // 设置文件存储路径
            String path = uploadPathConfig.getEventimgpath() + File.separator + fileName;
            File dest = new File(path);
            // 检测是否存在目录
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();// 新建文件夹
            }
            // 文件写入
            file.transferTo(dest);
            Map<String, Object> result = new HashMap<String, Object>();
            result.put("path", File.separator + fileName);
            return Result.ok().put("result", result);

        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Result.error("上传失败");
    }

图片路径到不同表字段中,并取路径后缀名

    @RequestMapping(value = "/files", method = RequestMethod.POST)
    public Result imgs(@RequestParam("file") MultipartFile[] file) {
        try {
            List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
            for (int i = 0; i < file.length; i++) {
                if (file[i].isEmpty()) {
                    return Result.error("文件为空");
                }
                // 获取文件名《后缀》
                String fileName = System.currentTimeMillis()+ file[i].getOriginalFilename();
                // 设置文件存储路径《后缀》
                String path = uploadPathConfig.getEventimgpath() + File.separator + fileName;
                File dest = new File(path);
                // 检测是否存在目录
                if (!dest.getParentFile().exists()) {
                    dest.getParentFile().mkdirs();// 新建文件夹
                }
                // 文件写入
                file[i].transferTo(dest);
                                《后缀名》
                String str =  fileName.substring(fileName.lastIndexOf(".") + 1);
                SysFile sysFile = new SysFile();
                sysFile.setFilepath(fileName);
                sysFile.setFilename(fileName);
                                    《后缀名写入。列如.jpg.mp4》
                sysFile.setSuffix(str);
                sysFileService.insert(sysFile);
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("fileid", sysFile.getFileid());
                list.add(map);
            }
            
            return Result.ok().put("result", list);
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Result.error("上传失败");
    }
    @RequestMapping(value = "/files", method = RequestMethod.POST)
    public Result imgs(@RequestParam("file") MultipartFile[] file) {
        try {
            List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
            for (int i = 0; i < file.length; i++) {
                if (file[i].isEmpty()) {
                    return Result.error("文件为空");
                }
                // 获取文件名《后缀》
                String fileName = System.currentTimeMillis()+ file[i].getOriginalFilename();
                // 设置文件存储路径《后缀》
                String path = uploadPathConfig.getEventimgpath() + File.separator + fileName;
                File dest = new File(path);
                // 检测是否存在目录
                if (!dest.getParentFile().exists()) {
                    dest.getParentFile().mkdirs();// 新建文件夹
                }
                // 文件写入
                file[i].transferTo(dest);
                                《后缀名》
                String str =  fileName.substring(fileName.lastIndexOf(".") + 1);
                SysFile sysFile = new SysFile();
                sysFile.setFilepath(fileName);
                sysFile.setFilename(fileName);
                                    《后缀名写入。列如.jpg.mp4》
                sysFile.setSuffix(str);
                sysFileService.insert(sysFile);
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("fileid", sysFile.getFileid());
                list.add(map);
            }
            
            return Result.ok().put("result", list);
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Result.error("上传失败");
    }

上传文件2

    @RequestMapping(value = "/uploadimages", method = RequestMethod.POST)
    public Result uploadExcel(HttpServletRequest request) {
        try {
            List<MultipartFile> files =((MultipartHttpServletRequest)request).getFiles("files");
            if (files.size() == 0) {
                return Result.error("文件为空");
            }
            JSONArray fileArr = new JSONArray();
            for(MultipartFile file : files){
                // 获取文件名
                String fileName = System.currentTimeMillis() + file.getOriginalFilename();
                // 设置文件存储路径
                String path = uploadPathConfig.getEventimgpath() + File.separator + fileName;
                File dest = new File(path);
                // 检测是否存在目录
                if (!dest.getParentFile().exists()) {
                    dest.getParentFile().mkdirs();// 新建文件夹
                }
                // 文件写入
                file.transferTo(dest);
                JSONObject fileObj = new JSONObject();
                fileObj.put("imgpath", File.separator + fileName);
                fileArr.add(fileObj);
            }
            return Result.ok().put("result", fileArr);
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Result.error("上传失败");
    }

下载文件

@RequestMapping(value = "/fileDownload", method = RequestMethod.POST)
    public Result downloadFile(HttpServletRequest request, HttpServletResponse response,String  fileName,String fileType) {
        String path=null;
        if (fileName != null) {
            // 设置文件存储路径
            switch (fileType) {
                case "1":
                    // 图片
                    path = uploadPathConfig.getEventimgpath();
                    break;
                case "2":
                    // excel文件
                    path = uploadPathConfig.getExcelpath();
                    break;
                case "3":
                    // 压缩包
                    path = uploadPathConfig.getZippath();
                    break;
                case "4":
                    // 文件
                    path = uploadPathConfig.getFilepath();
                    break;
                default:
                    path = uploadPathConfig.getEventimgpath();
                    break;
            }

        }
        File file = new File(path , fileName);
        if (file.exists()) {
            response.setContentType("application/force-download");// 设置强制下载不打开
            response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 设置文件名

            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                OutputStream os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer, 0, i);
                    i = bis.read(buffer);
                }
                System.out.println("success");
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }else{
            return Result.error("下载失败");
        }
        return Result.ok("下载成功");
    }

删除文件

@RequestMapping(value = "/delFile", method = RequestMethod.POST)
    public Result removeFileById(String fileid) {
        try {
            SysFile sysFile = sysFileService.selectById(fileid);
            File file=new File(uploadPathConfig.getEventimgpath()+"/"+sysFile.getFilepath());
            if(file.exists()&&file.isFile())
                file.delete();
            sysFileService.deleteById(fileid);
            return Result.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("图片删除失败");
        }
    }
    

 

图片-文件上传下载

标签:上传下载   tput   content   img   byte   buffere   bsp   tee   trace   

原文地址:https://www.cnblogs.com/yanchaohui/p/9953873.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!