xheditor-文件上传-Spring3 MVC-支持html5-application/octet-stream

阅读更多
xheditor1.1.5 版本文件上传使用html5-application/octet-stream
Spring3 MVC之前写的上传程序无法支持
@RequestMapping(value = "/upload")
    public String uploadFile(Model m, MultipartHttpServletRequest request) throws IOException {
        String path = UploadController.class.getResource("/").getPath().split("WEB-INF")[0] + "upload/";
        Iterator iterator = request.getFileNames();
        while (iterator.hasNext()) {
            String next = iterator.next();
            List files = request.getFiles(next);
            for (int i = 0; i < files.size(); i++) {
                if (!files.get(i).isEmpty()) {
                    byte[] bytes = files.get(i).getBytes();
                    String uploadFile = UploadUtils.generateFilename(path, UploadUtils.getExtension(files.get(i).getOriginalFilename(), "jpg"));
                    File file = new File(uploadFile);
                    FileOutputStream fos = new FileOutputStream(file);
                    fos.write(bytes);
                    fos.close();
                    m.addAttribute("url", uploadFile.replace(path, "/upload"));
                    m.addAttribute("local", uploadFile);
                }
            }
        }
        return "upload";
    }


需要改造如下:
@RequestMapping(value = "/upload", method = RequestMethod.POST)
    public String upload(Model m, HttpServletRequest request) throws IOException {
        String path = UploadController.class.getResource("/").getPath().split("WEB-INF")[0] + "upload/";
        if ("application/octet-stream".equals(request.getContentType())) { //HTML 5 上传
            try {
                String dispoString = request.getHeader("Content-Disposition");
                int iFindStart = dispoString.indexOf("filename =\"") + 10;
                int iFindEnd = dispoString.indexOf("\"", iFindStart);
                String sFileName = dispoString.substring(iFindStart, iFindEnd);
                int i = request.getContentLength();
                byte buffer[] = new byte[i];
                int j = 0;
                while (j < i) { //获取表单的上传文件
                    int k = request.getInputStream().read(buffer, j, i - j);
                    j += k;
                }
                if (buffer.length >= 0) { //文件是否为空
                    String uploadFile = UploadUtils.generateFilename(path, UploadUtils.getExtension(sFileName, "jpg"));
                    File file = new File(uploadFile);
                    OutputStream out = new BufferedOutputStream(new FileOutputStream(file, true));
                    out.write(buffer);
                    out.close();
                    m.addAttribute("url", uploadFile.replace(path, "/upload"));
                    m.addAttribute("local", uploadFile);
                }
            } catch (Exception ex) {
                m.addAttribute("err", ex.getMessage());
            }
        }
        return "upload";
    }

你可能感兴趣的:(HTML5,MVC,J#,Web,HTML)