1. 程式人生 > >單檔案上傳

單檔案上傳

1.新增依賴

 <!-- 檔案上傳 -->
 <dependency>
     <groupId>commons-fileupload</groupId>
     <artifactId>commons-fileupload</artifactId>
     <version>1.3.1</version>
 </dependency>
 <dependency>
     <groupId>commons-io</groupId>
     <artifactId>commons-io</artifactId>
     <version>2.4</version>
 </dependency>

2.jsp頁面開發

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();
%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>上傳檔案</title>
    </head>
    <body>
        <form action="<%=basePath%>/upload" method="post" enctype="multipart/form-data">

            上傳檔案:<input type="file" name="uploadFile">
            <input type="submit" value="上傳">
        </form>
    </body>
</html>

3.開發檔案上傳處理類

@Controller
public class FileController {
    //顯示檔案上傳頁面
    @RequestMapping(value = "/display")
    public ModelAndView display(){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("items/upload");
        return modelAndView;
    }

    //上傳處理
    @RequestMapping(value = "/upload")
    public ModelAndView upload(@RequestParam("uploadFile")MultipartFile file) throws Exception {
        ModelAndView modelAndView = new ModelAndView();
        if (!file.isEmpty()) {
            //1.取檔案格式字尾名
            String type = file.getOriginalFilename().substring(file.getOriginalFilename().indexOf("."));
            //2.取當前時間戳作為檔名
            String fileName = System.currentTimeMillis() + type;
            //3.設定存放位置
            String path = "E:\\程式碼存檔\\springmvc\\springMVC_demo\\src\\main\\java\\com\\steven\\ssm\\upload\\" + fileName;
            //4.建立檔案
            File destFile = new File(path);
            try {
                //5.複製臨時檔案到指定目錄下
                //FileUtils.copyInputStreamToFile()這個方法裡對IO進行了自動操作,不需要額外的再去關閉IO流
                FileUtils.copyInputStreamToFile(file.getInputStream(), destFile);
            } catch (IOException e) {
                e.printStackTrace();
            }
            modelAndView.setViewName("items/success");
        } else {
            modelAndView.setViewName("items/failed");
        }
        return modelAndView;
    }
}