SpringMvc 上傳圖片

1.導入必須的兩個包

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

在spring-mvc的配置xml文件裏配

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

bean 的id不能錯
2.前端頁面

<meta http-equiv="Content-Type" content="multipart/form-data;charset=utf-8" />
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>測試上傳</title>
</head>
<body>
<form  method="post" action="/userPicUpload" enctype="multipart/form-data" >
    <fieldset>
        <legend>用戶基本信息</legend>
        <p>
            <label for="userPic">頭像</label>
            <input id="userPic" name="userPic" type="file">
        </p>
        <p>
            <input class="submit" type="submit" value="提交">
        </p>
    </fieldset>
</form>
</body>
</html>

post傳遞,必須加上enctype=“multipart/form-data”
3.後臺接受

   @RequestMapping(value = "/userPicUpload",method = RequestMethod.POST)
    @ResponseBody
    public void userPicUpload(HttpServletRequest request,@RequestParam(value = "userPic",required = false)MultipartFile userPic)throws Exception {
        System.out.println("開始");
        String path = request.getSession().getServletContext().getRealPath("upload");
        String fileName = userPic.getOriginalFilename();
//        String fileName = new Date().getTime()+".jpg";
        System.out.println(path);
        File targetFile = new File(path, fileName);
        if(!targetFile.exists()){
            targetFile.mkdirs();
        }
        //保存
        try {
            userPic.transferTo(targetFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

注意MultipartFile 的名字要和前端圖片的name一樣,不然會null

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章