java springmvc4 图片或文件上传

博客围绕Java文件配置展开,介绍了配置文件解析和上传文件处理的核心方法,还给出了一个相关的不错API链接,可参考学习Spring MVC文件上传教程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、文件配置

  配置文件解析

  上传文件处理的核心方法

    // uploadOneFile.jsp, uploadMultiFile.jsp submit to.
    @RequestMapping(value = "/doUpload", method = RequestMethod.POST)
    public String uploadFileHandler(HttpServletRequest request, Model model,
                                    @RequestParam("file") MultipartFile[] files) {

        // Root Directory.
        String uploadRootPath = request.getServletContext().getRealPath(
                "upload");
        System.out.println("uploadRootPath=" + uploadRootPath);

        File uploadRootDir = new File(uploadRootPath);

        // Create directory if it not exists.
        if (!uploadRootDir.exists()) {
            uploadRootDir.mkdirs();
        }
        // 创建
        List<File> uploadedFiles = new ArrayList<File>();
        for (int i = 0; i < files.length; i++) {
            MultipartFile file = files[i];

            // Client File Name
            String name = file.getOriginalFilename();
            System.out.println("Client File Name = " + name);

            if (name != null && name.length() > 0) {
                try {
                    byte[] bytes = file.getBytes();

                    // Create the file on server
                    File serverFile = new File(uploadRootDir.getAbsolutePath()
                            + File.separator + name);

                    // Stream to write data to file in server.
                    BufferedOutputStream stream = new BufferedOutputStream(
                            new FileOutputStream(serverFile));
                    stream.write(bytes);
                    stream.close();

                    uploadedFiles.add(serverFile);
                    System.out.println("Write file: " + serverFile);
                } catch (Exception e) {
                    System.out.println("Error Write file: " + name);
                }
            }
        }
        model.addAttribute("uploadedFiles", uploadedFiles);
        return "uploadResult";
    }

  也可参见一个很不错的api连接:

    https://www.yiibai.com/spring_mvc/spring-mvc-file-upload-tutorial.html

转载于:https://www.cnblogs.com/wuzaipei/p/10571628.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值