springboot上傳單個文件,多個文件以及文件和表單數據同時提交

一直有小夥伴不知道springboot項目的文件上傳功能,今天我們就來搞懂它,讀完本篇文章你可以知道以下內容

  1. 單個文件上傳
  2. 多個文件上傳
  3. 文件與form表單普通屬性同時提交
  4. 通過ajax提交form表單(含文件上傳 )
  5. 文件下載(解決中文文件名亂碼)

首先來看前端html,一個頁面中同時實現了ajax方式提交表單(含附件)以及通過submit方式進行表單提交(帶附件)

<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" />
    <script src="/webjars/jquery/3.5.1/jquery.js"></script>
    <script src="http://libs.baidu.com/jquery/1.9.0/jquery.js" type="text/javascript"></script>
    <script type="text/javascript">
        var uploadFile = function () {
            var formdata = new FormData(document.getElementById("forms"));
            console.log(formdata);
            $.ajax({
                url:"/upload",
                type: "POST",
                data: formdata,
                processData:false,
                contentType:false,
                success:function(){
                    console.log("over...");
                },
                error: function (e) {
                    alert("錯誤")
                }
            })

        }

    </script>
</head>
<body>

<div class="container">

    <form class="form-signin" id="forms" th:action="@{/upload}" method="post" enctype="multipart/form-data">
        <h2 class="form-signin-heading">個人信息</h2>
        <input type="hidden" th:id="${person.id}" name="id" th:value="${person.id}"/>
        <div class="input-group">
            <span class="input-group-addon" id="basic-addon1">用戶名</span>
            <input type="text" class="form-control" placeholder="用戶名" id="userName" name="userName" th:value="${person.userName}" aria-describedby="basic-addon1">
        </div>
        <div class="input-group">
            <span class="input-group-addon" id="basic-addon2">&nbsp;&nbsp;&nbsp;</span>
            <input type="text" class="form-control" placeholder="age" id="age" name="age" th:value="${person.age}" aria-describedby="basic-addon1">
        </div>
        <div class="input-group">
            <span class="input-group-addon" id="basic-addon3">手機號</span>
            <input type="text" class="form-control" placeholder="mobile" id="mobile" name="mobile" th:value="${person.mobile}" aria-describedby="basic-addon1">
        </div>
        <div class="form-group">
            <label for="file">上傳附件</label>
            <input type="file" id="file" name="file" >
            <p class="help-block">Example block-level help text here.</p>
        </div><div class="form-group">
            <label for="files">上傳多附件</label>
            <input type="file" id="files" name="files" multiple>
            <p class="help-block">Example block-level help text here.</p>
        </div>
        <div class="btn-group" role="group">
                <button type="button" class="btn btn-primary btn-default" id="upload" onclick="uploadFile()">ajax上傳</button>
                <button type="submit" class="btn btn-primary btn-default" id="" >submit上傳</button>
        </div>
    </form>

</div> <!-- /container -->
</body>
</html>

後端代碼:

package com.myproject.springmybatis.controller;

import com.myproject.springmybatis.model.Person;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Controller
public class FileUploadController {

    @GetMapping("/upload")
    public String toUpload(ModelMap map){
        Person person = new Person();
        person.setPassword("!23456");
        person.setAge(18);
        person.setId(1L);
        person.setUserName("zhangsan");
        map.put("person", person);
        return "fileUpload";
    }

    @PostMapping("/upload")
    @ResponseBody
    public Map<String,Object> upload(Person person, @RequestParam("file") MultipartFile file,@RequestParam("files") MultipartFile[] files) throws IOException {
        Map<String,Object> map = new HashMap<>();
        String filePath = "/Users/xumingfei/Desktop/test/";
        System.out.println(person);
        if (!file.isEmpty()) {
            String contentType = file.getContentType();
            String filename = file.getOriginalFilename();

            file.transferTo(new File(filePath+filename));
            map.put("msg","上傳單個成功");
        }else {
            map.put("msg","上傳失敗");
        }
        for (MultipartFile f :
                files) {
            String fname = f.getOriginalFilename();
            f.transferTo(new File(filePath+fname));
            System.out.println(f.getOriginalFilename());

        }
        map.put("msg1","上傳多個附件成功");
        return map;
    }
    
    /**
     * 文件下載
     * @param request
     * @param response
     * @param fileName
     * @return
     * @throws IOException
     */
	@RequestMapping("/downloadFile")
    @ResponseBody
    public String download(HttpServletRequest request, HttpServletResponse response, @RequestParam("fileName") String fileName) throws IOException {
   		if (StringUtils.isEmpty(fileName)) {
            fileName = "test附件.doc";
        }
        if (fileName != null) {
            File file = new File("/Users/xumingfei/Desktop/test/"+fileName);
            if (file.exists()){
                String userAgent = request.getHeader("User-Agent");
                if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
                    fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
                } else {
                    // 非IE瀏覽器的處理:
                    fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
                }
                response.setContentType("application/force-download");
                response.addHeader("Content-Disposition","attachment;fileName="+fileName);
                byte[] buffer = new byte[1024];
                FileInputStream inputStream = null;
                BufferedInputStream bufferedInputStream = null;
                try {
                    inputStream = new FileInputStream(file);
                    bufferedInputStream = new BufferedInputStream(inputStream);
                    OutputStream os = response.getOutputStream();
                    int i = bufferedInputStream.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bufferedInputStream.read(buffer);
                    }
                    return "download success";
                } catch (Exception e) {
                    e.printStackTrace();
                }finally {
                    bufferedInputStream.close();
                    inputStream.close();
                }
            }
        }
        return "failure";
    }
}

大家喜歡的話不妨給小編點個贊吧!掃一掃關注公衆號不迷路。
在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章