1. 程式人生 > 實用技巧 >基於SpringMVC的圖片上傳

基於SpringMVC的圖片上傳

這兩天想做一個上傳圖片的demo,但是參考了很多部落格,依舊踩了很多坑,一方面也是自己的基礎欠缺,首先先介紹我踩的2個坑

第一:File的構造方法

public static void main(String[] args) {
        String filePath ="D:\\upload" ; //儲存圖片的路徑
        String newFileName=UUID.randomUUID().toString();
        File tagetFile = new File(filePath,newFileName);
        File tagetFile1 
= new File(filePath+newFileName); System.out.println(tagetFile); System.out.println(tagetFile1); } 輸出結果: D:\upload\d2d0c709-8889-4a76-8985-b81ce320de8a D:\uploadd2d0c709-8889-4a76-8985-b81ce320de8a

所以要注意File建構函式裡面是拼字串還是形成一個路徑還是父路徑拼子路徑 這點要注意!

第二:在展示頁面 的<img > 標籤中:不能加上全包名${pageContext.request.ContextPath},加上就是錯了

正確的寫法是:<img src="/image/${user.img}">使用者名稱:${user.username}

===================================================================================

下面是圖片上傳的流程,首先匯入2個包

 <!--上傳圖片相關-->
        <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.2.2</version>
        </dependency>

  在spring-mvc配置

<!--5.配置檔案上傳解析器-->
    <bean class="org.springframework.web.multipart.commons.CommonsMultipartResolver" id="multipartResolver">
        <property name="defaultEncoding" value="utf-8"></property>
        <property name="maxUploadSize" value="25000"></property>
    </bean>

首先是註冊介面:(我感覺應該新增一個拖拽的框框,用非同步載入圖片到這個框框上,這個待實現)

這裡要注意的是:

 method="post" enctype="multipart/form-data" 目的是多部份提交把表單形式按二進位制格式提交,表單name是file
<div class="container">
    <div class="row">
        <div class="col-md-12">
            <form action="${pageContext.request.contextPath}/user/imageUpload"  method="post" enctype="multipart/form-data">
                <div class="form-group">
                    <label for="Username">Username</label>
                    <input type="test" class="form-control" id="Username" placeholder="Username" name="username">
                </div>
                <div class="form-group">
                    <label for="exampleInputPassword1">Password</label>
                    <input type="password" class="form-control" id="exampleInputPassword1" placeholder="Password" name="password">
                </div>
                <div class="form-group">
                    <label for="birthday">birthday</label>
                    <input type="date" class="form-control" id="birthday" placeholder="birthday" name="birthday">
                </div>
                <div class="form-group">
                    <label for="file">File input</label>
                    <input type="file" id="file" name="file"  >

                </div>
                <div class="checkbox">
                    <label>
                        <input type="checkbox"> Check me out
                    </label>
                </div>
                <button type="submit" class="btn btn-default">Submit</button>
            </form>
        </div>
    </div>

</div>
然後是實體類:User:這裡注意我把 private MultipartFile file; 封裝在實體類中,還有Date型別在SpringMVC中要加上註解不然不成功
package com.mkx_test.domain;

import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;

public class User {
        private int id;
        private String username;
        private String password;

        @DateTimeFormat(pattern = "yyyy-MM-dd")
        private Date birthday;

        private String img;

        private MultipartFile file;

        public String getImg() {
            return img;
        }

        public void setImg(String img) {
            this.img = img;
        }

    public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public String getUsername() {
            return username;
        }

        public void setUsername(String username) {
            this.username = username;
        }

        public String getPassword() {
            return password;
        }

        public void setPassword(String password) {
            this.password = password;
        }

        public Date getBirthday() {
            return birthday;
        }

        public void setBirthday(Date birthday) {
            this.birthday = birthday;
        }

        public MultipartFile getFile() {
            return file;
        }

        public void setFile(MultipartFile file) {
            this.file = file;
        }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", birthday=" + birthday +
                ", img='" + img + '\'' +
                ", file=" + file +
                '}';
    }
}

Controller層

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping("/imageUpload")
    public String imageUpload(User user , Model model, HttpServletRequest request) throws IOException {
        /**
         * 上傳圖片
         */
        String filePath ="D:\\upload" ; //儲存圖片的路徑
        String newFileName =null ;
        if(!user.getFile().isEmpty()){
            //獲取原始圖片的拓展名
            String originalFilename = user.getFile().getOriginalFilename();//v2-b8b4c3500d2f56d826d1eba7dd684c3c_720w.jpg
            //新的檔名稱
            newFileName=UUID.randomUUID().toString().replaceAll("-","")+originalFilename;
            System.out.println("newFileName"+newFileName);//0a1ffe50-d91e-4ef8-aa7c-6b353154af03v2-b8b4c3500d2f56d826d1eba7dd684c3c_720w.jpg
            //封裝上傳檔案位置的全路徑
            //File tagetFile = new File(filePath,newFileName);
            //把本地檔案上傳到封裝上傳位置的全路徑
            user.getFile().transferTo(new File(filePath,newFileName));
        }

        user.setImg(newFileName);
        //儲存資訊
        userService.register(user);
        model.addAttribute("user",user);
        return "home";

    }

資料庫中:

圖片檔案的虛擬對映,因為圖片實際上是儲存在本地的磁碟中,而資料庫只存了相對路徑

展示頁面:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <style>
        img{
            width: 150px;
            height: 150px;

        }
    </style>
</head>
<body>
<div>

<img src="/image/${user.img}">使用者名稱:${user.username}

</div>
</body>
</html>