1. 程式人生 > >SpringMvc實現圖片上傳

SpringMvc實現圖片上傳

首先是設定一下tomcat的虛擬路徑,有兩種方法(以在C:/upfile/為例)

  • 第一種是在tomcat的bin目錄下的server.xml新增一句

< Context docBase=“C:/upfile/” path="/upload" reloadable=“false”/>
/upload就是虛擬路徑,在下面的檔案可以在瀏覽器localhost:8080 /upload/。。。訪問到

  • 第二種是在idea下的簡單設定,如下
  • 在這裡插入圖片描述

在這裡插入圖片描述

訪問localhost:8080/upfile/404.jpg
在這裡插入圖片描述

編寫一個簡單的檔案上傳頁面uploadPictureJsp.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2018/10/23
  Time: 13:48
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>上傳圖片</title>
</head>
<body>
<form action="/upfile.do" method="post" enctype="multipart/form-data">
    <c:if test="${picture!=null}">
        <img src="/upfile/${picture}" width="100px" height="100px">
    </c:if>
    <input type="file" name="picture">
    <input type="submit">
</form>
</body>
</html>

關於enctype問題可以看這裡

然後就是控制器類uploadFile,放在/uploadPicture下

需要匯入兩個包
在這裡插入圖片描述

package uploadPicture;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * Created by Administrator on 2018/10/23.
 */
@Controller
public class uploadFile {

    @RequestMapping("/upfile.do")
    public String upfile(Model model, HttpServletRequest request, MultipartFile picture)
            throws IOException {
//        String picrureName=request.getParameter("picture");
        request.setAttribute("picture",picture.getOriginalFilename());
        String picName= UUID.randomUUID().toString();
        String oriName=picture.getOriginalFilename();
        String extName=oriName.substring(oriName.lastIndexOf("."));

        picture.transferTo(new File("C:/upfile1/"+picName+extName));
        System.out.println(request.getParameter("picture"));
        return "forward:/uploadPictureJsp.jsp";
    }
}

需要在springmvc的配置檔案demo1.xml配置一下

<!-- 檔案上傳,id必須設定為multipartResolver -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 設定檔案上傳大小 5M -->
        <property name="maxUploadSize" value="5000000" />
    </bean>

ok,簡單的上傳檔案的demo完成了