Spring MVC上传文件MultipartFile配置以及简单使用

来源:互联网 发布:阿斗 知乎 编辑:程序博客网 时间:2024/06/01 10:13

pom

    <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->        <dependency>            <groupId>commons-fileupload</groupId>            <artifactId>commons-fileupload</artifactId>            <version>1.2.1</version>        </dependency>        <!-- https://mvnrepository.com/artifact/commons-io/commons-io -->        <dependency>            <groupId>commons-io</groupId>            <artifactId>commons-io</artifactId>            <version>2.4</version>        </dependency>

spring-mvc添加配置

    <bean id="multipartResolver"        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">        <property name="defaultEncoding" value="utf-8"></property>        <property name="maxUploadSize" value="10485760000"></property>        <property name="maxInMemorySize" value="40960"></property>    </bean></beans>

Utils

    /**     * 图片文件上传     */    public Result<String> ImageUpload(MultipartFile file) {        Result<String> result = new Result<>();        String realPath = "d:\\files\\";        String path = "";        String savePaths = "";        if (file != null) {// 判断上传的文件是否为空            String type = null;// 文件类型            String fileName = file.getOriginalFilename();// 文件原名称            // 判断文件类型            type = fileName.indexOf(".") != -1 ? fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length())                    : null;            if (type != null) {                // 判断文件类型是否为空                if ("GIF".equals(type.toUpperCase()) || "PNG".equals(type.toUpperCase())                        || "JPG".equals(type.toUpperCase())) {                    // 自定义的文件名称                    String trueFileName = String.valueOf(System.currentTimeMillis()) + fileName;                    // 设置存放图片文件的路径                    path = realPath + trueFileName;                    System.out.println("存放图片文件的路径:" + path);                    // 转存文件到指定的路径                    try {                        file.transferTo(new File(path));                    } catch (IllegalStateException | IOException e) {                        // TODO Auto-generated catch block                        e.printStackTrace();                    }                    savePaths = path;                    result.setObj(savePaths);                } else {                    System.out.println("Wrongtype");                    result.setSuccess(false);                }            } else {                System.out.println("文件类型为空");                result.setSuccess(false);            }        }        return result;    }

请求代码:

    @RequestMapping(value="insertExceptionPic",method=RequestMethod.POST)    @ApiOperation("上传异常图片")    @ResponseBody    public Result<String> uploadExceptionPicture(@RequestParam("file") MultipartFile file)    {        return utils.ImageUpload(file);    }

这里写图片描述

这里写图片描述

上传成功

阅读全文
0 0
原创粉丝点击