基於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>

 

 

 



 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM