zoukankan      html  css  js  c++  java
  • java----上传文件单独接口

    图片做一个单独的

    //上传图片,返回attach_id
    @RequestMapping(value = "/addImg")
    public BaseResponse addImg(HttpServletRequest request, @RequestParam("file") MultipartFile file, String flag) throws UnsupportedEncodingException {
    request.setCharacterEncoding("utf-8");
    BaseResponse msg = new BaseResponse();
    //做文件上传
    if ("".equals(file.getName()) || file.isEmpty()) {
    new BizException(ErrorCode.WRONG_FILE_FULL.getDesc());
    }
    if (file.getSize() > 3000000) {
    new BizException(ErrorCode.WRONG_FILE_UPLOAD_PASS.getDesc());
    }
    //附件对象
    Attach attach = new Attach();
    String path = uploadPath + File.separator;
    File dir = new File(path);
    if (!dir.exists()) {
    dir.mkdirs();
    }
    long attach_id = Long.valueOf(0);
    //判断文件
    if (!file.isEmpty()) {
    //上传的文件的名称
    String oldFileName = file.getOriginalFilename();
    attach.setName(oldFileName.substring(0, oldFileName.lastIndexOf(".")));
    //取文件名的后缀
    String suffix = oldFileName.substring(oldFileName.lastIndexOf("."));
    //判断文件格式和类型 GIF,PNG 或JPG
    if (".jpg".equalsIgnoreCase(suffix)) {
    attach.setType("jpg");
    } else if (".png".equalsIgnoreCase(suffix)) {
    attach.setType("png");
    } else if (".gif".equalsIgnoreCase(suffix)) {
    attach.setType("gif");
    } else if (".doc".equalsIgnoreCase(suffix)) {
    attach.setType("doc");
    } else if (".word".equalsIgnoreCase(suffix)) {
    attach.setType("word");
    } else if (".pdf".equalsIgnoreCase(suffix)) {
    attach.setType("pdf");
    } else if (".docx".equalsIgnoreCase(suffix)) {
    attach.setType("docx");
    } else {
    new BizException(ErrorCode.WRONG_FILE_UPLOAD_FORMAT.getDesc());
    }
    Long id = Utils.nextId();
    //新的文件名
    String fileName = id + suffix;
    path = path + fileName;
    attach.setAddress(path);
    attach.setFlag(flag);
    attach.setTime(Utils.getDate());
    //文件保存路径
    File savePath = new File(path);
    //设置附件路径
    try {
    attach_id = attachService.addAttach(attach);
    //通过封装好的方法将文件上传到指定的文件夹
    file.transferTo(savePath);
    } catch (IOException e) {
    new BizException(ErrorCode.WRONG_FILE_UPLOAD.getDesc());
    }
    }
    msg.setData(attach_id);
    msg.setSuccess(true);
    return msg;
    }
  • 相关阅读:
    golang学习 ---并发获取多个URL
    MySQL的my.cnf文件(解决5.7.18下没有my-default.cnf)
    Python ElasticSearch API
    linux 输出重定向 何时会写文件
    Linux top命令的用法详细详解
    mysql 5.7.13 安装配置方法(linux)-后期部分运维
    linux下各目录的作用
    MySQL 获得当前日期时间 函数
    mysql导入大批量数据出现MySQL server has gone away的解决方法
    python之MySQL学习——防止SQL注入
  • 原文地址:https://www.cnblogs.com/Darkqueen/p/10968806.html
Copyright © 2011-2022 走看看