SpringMVC实现图片上传以及该注意的小细节

先附上图片上传的代码

jsp代码如下:

<form action="${path}/upload/uploadPic.do" method="post" enctype="multipart/form-data">      
<div>
       ![](${path}/mall/image/load_image.png)
       <input type="file" id="input-image" name="input-image">
       <input id="input-relative-path" name="imgs" type="hidden" >
       <input id="input-last-path" type="hidden">
       <input type="submit" value="上传图片">
 </div>
</form>

controller代码:通过spring的方式实现

@Controller
@RequestMapping("/upload")
public class UploadController extends BaseController {
    @RequestMapping(value = "/uploadPic", method = RequestMethod.POST)
    @LoginCheck
    public void uploadPic(HttpServletRequest request, PrintWriter out, String lastRealPath) throws IOException {
        // 将当前上下文初始化给CommonsMultipartResolver
        CommonsMultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        // 检查form中是否有enctype="multipart/form-data"
        if (resolver.isMultipart(request)) {
            // 强制转化request
            MultipartHttpServletRequest req = (MultipartHttpServletRequest) request;
            // 从表单获取input名称
            Iterator<String> iterable = req.getFileNames();
            // 存在文件
            if (iterable.hasNext()) {
                String inputName = iterable.next();
                // 获得文件
                MultipartFile mf = req.getFile(inputName);
                byte[] mfs = mf.getBytes();
                // 定义文件名
                String fileName = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
                Random random = new Random();
                for (int i = 0; i < 3; i++) {
                    fileName = fileName + random.nextInt(10);
                }
                // 获得后缀名
               String oriFileName = mf.getOriginalFilename();
               String suffix = oriFileName.substring(oriFileName.lastIndexOf("."));
              
               // 上传图片到本地
               String localPath = "/Users/ZR/Desktop/webPro/console/src/main/webapp/image/" + fileName + suffix;
               mf.transferTo(new File(localPath));

               // 获取图片的宽高
               BufferedImage bufferedImage = ImageIO.read(new FileInputStream(new File(localPath)));
               int width = bufferedImage.getWidth();
               int height = bufferedImage.getHeight();
               // 获取文件大小
               long size = mf.getSize();
            }
        }
    }
}

spring-mvc.xml代码:

 <!--
    文件上传的视图解析器,id值是固定的
 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="maxUploadSize" value="1024000"/>
    <!-- 其他属性 -->
</bean>

功能的实现其实很简单,但是对于初学者还是需要注意如下几个点

  • form上的enctype="multipart/form-data"不能忘记。
  • <input type="file" onchange="submitUpload()" id="input-image" name="input-image">name标签可以随便取名,但是不能忽略,否则Iterator<String> iterable = req.getFileNames();这边获取的集合将为空。

不注重细节只会让自己花更多的时间去debug

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,991评论 19 139
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,971评论 6 342
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,767评论 18 399
  • 本章主要内容: 备用的Spring MVC配置项 处理文件上传 控制器中的异常处理 使用flash属性 “等等,客...
    hoxis阅读 3,541评论 1 26
  • 这两天都在看一枚93少年的故事,他和KK都是我收集少年成长旅程所具有的代表人物,愿今后的我不曾浪费掉每一分钟。 当...
    海豚的世界阅读 323评论 0 0