码迷,mamicode.com
首页 > Web开发 > 详细

多文件上传demo

时间:2018-10-16 17:34:08      阅读:181      评论:0      收藏:0      [点我收藏+]

标签:sub   demo   div   存在   pos   tor   last   tac   ati   

@ApiOperation(value = "批量上传", notes = "批量上传", httpMethod = "POST")
    @PostMapping(value = "/upload")
    public void upload(HttpServletRequest request) {
        MultipartHttpServletRequest multipartRequest=(MultipartHttpServletRequest)request;
        String savePath="E:/test/";

        //保证目录存在
        File dir = new File(savePath);
        if (!dir.isDirectory()) {
            dir.mkdirs();
        }

        Iterator<String> it = multipartRequest.getFileNames();
        while (it.hasNext()) {
            MultipartFile multipartFile = multipartRequest.getFile(it.next());
            if (multipartFile != null) {
                String originName = multipartFile.getOriginalFilename();
                int subIdx = originName.lastIndexOf(".");
                String suffix = originName.substring(subIdx);//文件后缀
                File file;
                String showName;
                while (true) {
                    showName = UUID.randomUUID().toString().replaceAll("-", "") + suffix;//文件名称
                    file = new File(savePath + showName);
                    if (!file.exists()) {
                        break;
                    }
                }
                byte[] buffer = new byte[1024];
                try (OutputStream os = new FileOutputStream(file);
                     InputStream is = multipartFile.getInputStream()){
                    while (is.read(buffer) != -1) {
                        os.write(buffer);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

  

多文件上传demo

标签:sub   demo   div   存在   pos   tor   last   tac   ati   

原文地址:https://www.cnblogs.com/tinyj/p/9798712.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!