java文件上传至服务器与文件的删除

一、文件上传(到服务器中)代码如下:

    /**
     * 上传文件
     * @param file 文件
     * @param request HttpServletRequest
     * @return 返回文件基本信息
     */
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ResponseBody
    public ResponseData uploadImg(@RequestParam("file") MultipartFile file,
            HttpServletRequest request) {
        if (file == null) {
            return ResponseData.notFound().putDataValue("key", "file is null");
        }
        FileAttribute attribute = new FileAttribute();
        //获取上传文件的原名
        String fileName = file.getOriginalFilename();
        //获取文件后缀
        String suffix = getFileNameWithSuffix(fileName);
        String filePath = "";
        try {
            //得到上传路径
            filePath = URLDecoder.decode(getUploadPath(request), "utf-8");
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }
        String fileUploadName = new Date().getTime() + "." + suffix;
        //物理路径
        String fileUploadPath = filePath + fileUploadName;
        attribute.setSuffix(suffix);
        attribute.setName(fileUploadName);
        //        //windows路径‘\\’替换为‘/’
        //        String path = StringUtils.substringAfterLast(fileUploadPath, "webapp");
        //        if (path.contains("\\")) {
        //            path = filePath.replace("\\", "/");
        //        }
        attribute.setUrl(fileUploadPath);
        if (StringUtils.isNotBlank(fileName)) {
            try {
                File dir = new File(filePath);
                if (!dir.exists()) {
                    dir.mkdir();
                }
                File serverFile = new File(fileUploadPath);
                file.transferTo(serverFile);
            } catch (Exception e) {
                e.printStackTrace();
                return ResponseData.notFound().putDataValue("key",
                        "uploadimg fail");
            }
            /**
             * 项目服务器地址路径
             */
            String projectServerPath = request.getScheme() + "://" + request.getServerName() + ":" 
                           + request.getServerPort() + request.getContextPath() + "/upload/";
            System.out.println(projectServerPath);
            Map<String,Object> map = new HashMap<String,Object>();
            map.put("fileName", fileName);
            map.put("suffix", suffix);
            map.put("size", file.getSize());
            map.put("url", projectServerPath + fileUploadName);
            return ResponseData.ok().putDataValue("info", map);
        } else {
            return ResponseData.notFound().putDataValue("key",
                    "File suffix is invalid");
        }
    }
    //得到上传路径
    private String getUploadPath(HttpServletRequest request) {
        String path = "";
        int length = 0;
        int i = 0;
        String orginionPath = "";
        //判断是什么系统
        if ("\\".equals(File.separator)) {
            path = ClassUtils.getDefaultClassLoader().getResource("").getPath().substring(1);
            length = request.getContextPath().substring(1).length();
            i = path.indexOf(request.getContextPath().substring(1));
            orginionPath = path.substring(0, i + length);
            orginionPath = orginionPath.replace("/", File.separator);
            orginionPath = orginionPath + File.separator + "src" + File.separator + "main"
                + File.separator + "webapp" + File.separator + "upload" + File.separator;
        } else {
            System.out.println("----linux-----");
            path = ClassUtils.getDefaultClassLoader().getResource("").getPath();
            length = request.getContextPath().length();
            i = path.indexOf(request.getContextPath().substring(1));
            orginionPath = path.substring(0, i + length);
            orginionPath = orginionPath.replace("\\", File.separator);
            orginionPath = orginionPath + File.separator + "src" + File.separator + "main"
                  + File.separator + "webapp" + File.separator + "upload" + File.separator;
            orginionPath = orginionPath.substring(5);
            System.out.println("orginionPath=" + orginionPath);
        }
        return orginionPath;
    }

    /**
     * 保留文件名及后缀
     */
    public String getFileNameWithSuffix(String pathandname) {
        File file = new File(pathandname);
        String fileName = file.getName();
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
        return suffix;
    }

    /**
     * 图片限制
     *
     * @param fileName 全路径
     * @return
     */
    public boolean checkSuffix(String fileName) {
        String suffix = getFileNameWithSuffix(fileName);
        if (suffix.equals("jpg") || suffix.equals("png")) {
            return true;
        }
        return false;
    }

    public class FileAttribute {
        private String name;
        private String suffix;
        private String url;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getSuffix() {
            return suffix;
        }

        public void setSuffix(String suffix) {
            this.suffix = suffix;
        }

        public String getUrl() {
            return url;
        }

        public void setUrl(String url) {
            this.url = url;
        }
    }

二、文件删除

在删除文件之前必须首先得到文件的绝对路径,根据系统在本地文件中在的路径进行文件的删除,具体代码如下:

                        //取得当前主机存放项目的绝对路径
                        String workPath = System.getProperty("user.dir");
                        //得到文件名
                        String fileUrl = bookShareItem.getFileUrl();
                        int beginIndex = fileUrl.lastIndexOf("/");
                        int endIndex = fileUrl.length();
                        String substring = fileUrl.substring(beginIndex + 1, endIndex);
                        //获得文件存放的绝对路径
                        String fullFilePath = workPath + File.separator
                                + "aa\\bb\\cc\\upload" + File.separator
                                + substring;
                        //删除文件
                        File deleteFile = new File(fullFilePath);
                        if (deleteFile.exists() && deleteFile.isFile()
                                && deleteFile.delete() == true) {
                            fileFlag = true;
                        }

 

  • 4
    点赞
  • 38
    收藏
    觉得还不错? 一键收藏
  • 12
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 12
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值