springmvc之上传图片

在页面form中提交enctype="multipart/from-data"的数据时,需要springmvc对multipart类型的数据进行解析。

在springmvc.xml中配置解析这种类型数据的解析器。

配置解析器需要提前配置依赖

          <dependency>
             <groupId>commons-fileupload</groupId>
             <artifactId>commons-fileupload</artifactId>
             <version>1.2.2</version>
          </dependency>
          <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.5</version>
          </dependency>
</bean>
	<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="utf-8" />
        <!-- 上传图片最大大小-->
        <property name="maxUploadSize" value="10485760000" />
        <property name="maxInMemorySize" value="40960" />
    </bean>

之后要创建虚拟目录存储图片,这里不再赘述,

第一种图形化界面改

详情见https://blog.csdn.net/hexinghua0126/article/details/79189481

第二种直接修改tomcat的配置:

在conf/server.xml文件,添加虚拟目录

<Context docBase="物理路径(例如F:\develop\upload\temp)" path = "\pic" reloadable="false"

注意:在图片虚拟目录中,一定将图片分级创建,提高i/o性能。

//上传图片
            //controller中传参MultipartFile item_pic

            if(item_pic!=null){
                //存储图片的物理路径
                String pic_path = "F:\\develop\\upload\\temp\\";
                //原始名称
                String originalFilename = item_pic.getOriginalFilename();
                //新图片名称
                String newFileName = UUID.randomUUID()+originalFilename.substring(originalFilename.lastIndexOf("."));
                File newFile = new File(pic_path + newFileName);
                //将内存中的数据写入磁盘
                item_pic.transferTo(newFile);
                //将新图片名称写到itemsCustom
                itemsCustom.setPic(newFileName);
            }

猜你喜欢

转载自blog.csdn.net/qq_27817327/article/details/82682253