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;
    }
  • 相关阅读:
    C# 2.0 中Iterators的改进与实现原理浅析
    C#窗口关闭时最小化到托盘
    设计模式有趣解释
    序列化学习
    线程学习
    正则表达式
    .net内存回收与Dispose﹐Close﹐Finalize方法 [摘]
    5.匿名函数lambda
    2dns服务器解析创建
    2.ftp匿名
  • 原文地址:https://www.cnblogs.com/Darkqueen/p/10968806.html
Copyright © 2011-2022 走看看