天天看點

spingmvc 檔案上傳一、單檔案上傳二、多檔案上傳

一、單檔案上傳

1.jar包

spingmvc 檔案上傳一、單檔案上傳二、多檔案上傳

2.springmvc-servlet.xml配置

添加以下代碼

<!-- 檔案上傳設定 -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="utf-8"></property>
        <property name="maxUploadSize" value="10485760000"></property>
        <property name="maxInMemorySize" value="4069"></property>
    </bean>
           

3.jsp頁面編寫

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>單檔案上傳</title>
</head>
<body>

    <div style="margin: 0 auto; margin-top: 100px;">
        <form action="oneUpload.html" method="post" enctype="multipart/form-data">
            <p>
                <span>檔案</span>
                <input type="file" name="imageFile"> 
            </p>
            <p>
                <input type="submit" value="送出">
            </p>
        </form>
    </div>
</body>
</html>
           

4.controller檔案編寫

package com.Intimate.Controller;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.upload.Common.ToolUtil;


@Controller
public class UploadController {

    @RequestMapping("/oneUpload")
    public String oneUpload(@RequestParam("imageFile") MultipartFile imageFile, HttpServletRequest request){

        String uploadUrl = "F:\\image\\";
        String originalFilaname = imageFile.getOriginalFilename();      //拿到圖檔的原始名稱

        String newFilename = ToolUtil.makeFileNameByTime(originalFilaname);

        //判斷檔案路徑是否存在,如果不存在則建立檔案路徑
        File dir = new File(uploadUrl);
        if(!dir.exists()){
            dir.mkdirs();
        }

        System.out.println("檔案上傳到:" + uploadUrl + newFilename);

        //判斷上傳檔案是否存在,如果不存在則建立檔案
        File targetFile = new File(uploadUrl + newFilename);
        if(!targetFile.exists()){
            try {
                targetFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        //把上傳的檔案移動到targetFile中,即将記憶體中的資料寫入磁盤中
        try {
            imageFile.transferTo(targetFile);
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        request.setAttribute("imageName", newFilename);
//      return "redirect:http://localhost:8080/springmvc_upload/upload/" + filaname;
        return "uploadResult";

    }

}
           

5.工具類編寫

package com.upload.Common;

import java.text.SimpleDateFormat;

public class ToolUtil {

    public static String makeFileNameByTime(String filename){  
        String fileExtName = filename.substring(filename.lastIndexOf(".")+);
        //為防止檔案覆寫的現象發生,要為上傳檔案産生一個唯一的檔案名
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy_MM_dd_HHmmss");
        String time = sdf2.format(new java.util.Date());
        return time + "."+fileExtName;
    }

    public static String makeFileNameRand(String filename){  
        String fileExtName = filename.substring(filename.lastIndexOf(".")+);

        return UUID.randomUUID() + "."+fileExtName;
    }
}
           

7.結果展示頁面編寫

<title>多檔案上傳結果</title>
</head>
<body>
    <div style="margin: 0 auto; margin-top: 100px;">

        <img alt="" src="/pic/${imageName}">
    </div>
</body>
</html>
           

/pic 是tomact的虛拟路徑,對應着磁盤的一個實體途徑,也就是上面圖檔上傳的路徑

設定步驟:

1.打開server面闆

spingmvc 檔案上傳一、單檔案上傳二、多檔案上傳

2.輕按兩下server,打開設定界面

spingmvc 檔案上傳一、單檔案上傳二、多檔案上傳

3.點選Add External Web Module按鈕,選擇路徑

spingmvc 檔案上傳一、單檔案上傳二、多檔案上傳

Document base 就是存放圖檔的實體路徑;

Path 是虛拟路徑的名稱,記得 / 不能忘記;

點選ok,就完成了。

如果上面的方法沒反應,還有一種直接改配置檔案的方法:

打開tomact檔案夾下的conf檔案下的Server.xml檔案

<Host></Host>

中最後加一句

儲存即可

如果改配置檔案也沒用,那可能是用eclipse,有一個Server檔案夾

spingmvc 檔案上傳一、單檔案上傳二、多檔案上傳

那麼就需要改Server中的server.xml

二、多檔案上傳

jar包和springmvc-servlet.xml的設定和單檔案上傳一緻,隻需要修改jsp頁面和controller檔案即可

1.jsp頁面編寫

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>多檔案上傳</title>
</head>
<body>

    <div style="margin: 0 auto; margin-top: 100px;">
        <form action="moreUpload.html" method="post" enctype="multipart/form-data">
            <p>
                <span>檔案1:</span>
                <input type="file" name="imageFile1"> 
            </p>
            <p>
                <span>檔案2:</span>
                <input type="file" name="imageFile2"> 
            </p>
            <p>
                <input type="submit" value="送出">
            </p>

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

2.contorller檔案編寫

package com.Intimate.Controller;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.upload.Common.ToolUtil;


@Controller
public class UploadController {

    @RequestMapping("/moreUpload")
    public String moreUpload(HttpServletRequest request){

        MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> files = multipartHttpServletRequest.getFileMap();

//      String uploadUrl = request.getSession().getServletContext().getRealPath("/") +"upload/";
        String uploadUrl = "F:\\image\\";
        //判斷檔案路徑是否存在,如果不存在則建立檔案路徑
        File dir = new File(uploadUrl);
        if(!dir.exists()){
            dir.mkdirs();
        }

        List<String> fileList = new ArrayList<String>();

        for(MultipartFile file : files.values()){

            String originalFilaname = file.getOriginalFilename();      //拿到圖檔的原始名稱
            String newFilename = ToolUtil.makeFileNameRand(originalFilaname);

            File targetFile = new File(uploadUrl + newFilename);
            if(!targetFile.exists()){
                try {
                    targetFile.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                //把上傳的檔案移動到targetFile中
                try {
                    file.transferTo(targetFile);
                    fileList.add(newFilename);
                } catch (IllegalStateException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        request.setAttribute("files", fileList);

        return "uploadResult";
    }

}
           

3.結果展示頁面編寫

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>多檔案上傳結果</title>
</head>
<body>
    <div style="margin: 0 auto; margin-top: 100px;">
         <%
            List<String> fileList = (List)request.getAttribute("files");
            for(String url : fileList){
                %>
                <a href="/pic/<%=url%>">
                    <img alt="" src="/pic/<%=url%>">
                </a>
                <%
            }
        %> 
    </div>
</body>
</html>
           

–End