Java中:图片/文件的上传

Java中如何上传图片/文件等..?


第一步:更改我们的form表单为多文件方式

<form id="itemForm" action="${pageContext.request.contextPath }/updateitem.action" method="post" enctype="multipart/form-data">

第二步:配置我们的tomcat的虚拟目录,所有的文件上传都到这个目录来

这里写图片描述

第三步:导入上传文件必须依赖的两个jar包

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

第四步:配置我们的图片上传的解析器

    <!-- 配置我们的文件上传解析器,用于限制我们图片的格式,图片的大小等 -->
        <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
            <!-- 限制每个文件的最大值  为5M,单位为字节数组-->
            <property name="maxUploadSize" value="5242880"></property>
        </bean>

第五步:Jsp页面通过input来选择文件

<tr>
    <td>商品图片</td>
    <td>
        <c:if test="${item.pic !=null}">
            <img src="/pic/${item.pic}" width=100 height=100/>
            <br/>
        </c:if>
        <input type="file"  name="pictureFile"/> 
    </td>
</tr>

第六步:Controller后台接收文件

@RequestMapping("/updateitem.action")
    public String updateItem(Items items,MultipartFile pictureFile) throws IllegalStateException, IOException{
        //打印出来就是abc.png
        String originalFilename = pictureFile.getOriginalFilename();

        //获取我们uuid的字符串
        String random = UUID.randomUUID().toString();

        //截取我们文件名的后缀
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));

        //获取我们文件的最新的名称
        String newFileName = random+substring;

        //通过File.separator来获取我们文件上传的路径的分隔符,这个会自动的根据服务器的类型来判断用什么分隔符
        //如果是linux是/
        //如果是windows \\
        File file = new File("F:\\picupload"+File.separator+newFileName);

        //将我们上传的文件转移到目标文件当中去
        pictureFile.transferTo(file);

        System.out.println(originalFilename);
        itemService.updateItem(items);
        return "success";
    }
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值