input file文件上传_一文讲清楚文件上传下载那些事

点击上方“迷途中的小码农”,选择“置顶公众号”,技术文章第一时间送达!640f894ee0bb332f4aacc578bac0e01c.png

读完本文你将学会:

  1. 单个文件上传

  2. 多个文件上传

  3. 文件与form表单普通属性同时提交

  4. 通过ajax提交form表单(含文件上传 )

  5. 文件下载(解决中文文件名乱码)

许多同学一直搞不清楚单文件上传,多文件上传以及文件上传时同时与普通表单属性一起提交的问题,今天通过本文章我们来讲清楚。

首先,前端页面

<html lang="zh" xmlns:th="http://www.thymeleaf.org"><head>    <meta charset="UTF-8">    <title>Titletitle>    <link href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/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">        /**         * 通过ajax方式提交表单与附件         */        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">年   龄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 btn-group-justified" role="group" aria-label="...">            <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>        div>    form>div> body>html>

前端页面写完了,那么我们来看一下后端,controller

package com.myproject.springmybatis.controller;import com.myproject.springmybatis.model.Person;import com.sun.deploy.net.HttpResponse;import org.springframework.stereotype.Controller;import org.springframework.ui.ModelMap;import org.springframework.web.bind.annotation.*;import org.springframework.web.multipart.MultipartFile;import org.thymeleaf.util.StringUtils;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.*;import java.util.HashMap;import java.util.Map;@Controllerpublic 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;    }    @GetMapping("/download")    public String down(){        return "download";    }    /**     * 文件下载     * @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";    }}

注意:

1. 需要注意的是多文件上传使用input时需要添加multiple

type="file" id="files" name="files" multiple>

type="file" id="files" name="files" multiple="multiple">

2. 文件下载需要注意中文乱码的问题

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

通过这段代码就可以解决中文乱码啦!今天就学习到这里吧,我们下次见。

8a48d5f402e7361b2454b6fa5531cd87.png

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值