天天看点

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";
    }
}

           

大家喜欢的话不妨给小编点个赞吧!扫一扫关注公众号不迷路。

springboot上传单个文件,多个文件以及文件和表单数据同时提交
springboot上传单个文件,多个文件以及文件和表单数据同时提交
springboot上传单个文件,多个文件以及文件和表单数据同时提交

继续阅读