zoukankan      html  css  js  c++  java
  • 【Java__文件上传】web页面同时上传文件和参数

    code

        @RequestMapping("/uploadFile")
        @ResponseBody
        public AjaxResult uploadFile(HttpServletRequest request, HttpServletResponse response) throws Exception {
            boolean isMultipart = ServletFileUpload.isMultipartContent(request);
            if (!isMultipart) {
                return new AjaxResult(0, "isMultipart error");
            }
            String type = request.getParameter("type");
            if (StrUtils.isEmpty(type)) {
                return new AjaxResult(0, "type error");
            }
            boolean isOk = false;
            String imgUrl = "";
            try {
                // FileItem 是表单中的每一个元素的封装  创建一个 FileItem 的工厂类
                FileItemFactory factory = new DiskFileItemFactory();
                // 创建一个文件上传处理器(装饰设计模式)
                ServletFileUpload upload = new ServletFileUpload(factory);
                // 解析请求
                List<FileItem> items = upload.parseRequest(request);
                for (FileItem fileItem : items) {
                    if (fileItem.isFormField()) {
                        continue;
                    }
                    String savePathDir = request.getServletContext().getRealPath("/upload/" + getExId(request) + "/" + type + "/");
                    File file = new File(savePathDir);
                    if (!file.exists()) file.mkdir();
                    String fileName = UUID.randomUUID() + fileItem.getName().substring(fileItem.getName().lastIndexOf("."));
                    fileItem.write(new File(savePathDir + fileName));
                    imgUrl = request.getContextPath() + "/upload/" + getExId(request) + "/" + type + "/" + fileName;
                    isOk = true;
                    break;
                }
            } catch (Exception e) {
                e.printStackTrace();
                logger.error(e.getMessage());
                return AjaxResult.fail();
            }
            AjaxResult ajaxResult = AjaxResult.success();
            if (isOk) {
                ajaxResult.getMap().put("filename", imgUrl);
            } else {
                ajaxResult.setCode(0);
                ajaxResult.setMsg("上传失败");
                File file = new File(imgUrl);
                if (file.exists()) {
                    file.delete();
                }
            }
            return ajaxResult;
        }
    
  • 相关阅读:
    ios7 苹果原生二维码扫描(和微信类似)
    ios7之后 根据UILabel的文字计算frame的方法
    [Luogu1944] 最长括号匹配
    [bzoj3916] friends
    [NOIp2006] 能量项链
    [NOIp2003] 加分二叉树
    [Luogu1353] 跑步Running
    [Luogu2214] Mooo Moo S
    [POJ2452] Sticks Problem
    [POJ2406] Power Strings
  • 原文地址:https://www.cnblogs.com/kikyoqiang/p/13039385.html
Copyright © 2011-2022 走看看