javaweb文件上传和下载

简介: javaweb文件上传和下载

案例1:

前端页面

<div>
 <form class="form-signin" id="addSongFormId" enctype="multipart/form-data" method="post">
歌曲:
<input type="file" id="fileSongId" class="custom-file-input"
                                   name="song">
歌手:
 <input type="text" class="form-control mr-sm-2"
                                   name="songAuthor">
类型:
 
<select class="custom-select-override " name="songLanguageType">
                            <option value="1">华语</option>
                            <option value="2">日韩</option>
                            <option value="3">欧美</option>
                        </select>
</form>
</div>

js代码

<script>
    $(function () {
        //处理上传
        var maxSongSize = 1024 * 1024 * 20;//文件最大10M
        var songFormat = ["mp3"];
        $("#addSongFormId").submit(function () {
            var song = $('#fileSongId').get(0).files[0];
            //判定格式
            if (song == null) {
                $('#collapse-file-error-hint').html("请选择歌曲文件");
                $('#collapse-file-error-hint').collapse();
                return false;
            } else if (song.size > maxSongSize) {
                $('#collapse-file-error-hint').html("超出文件最大限制");
                $('#collapse-file-error-hint').collapse();
                return false;
            } else if (songFormat.indexOf(song.name.substr(song.name.lastIndexOf(".") + 1)) == -1) {
                $('#collapse-file-error-hint').html("歌曲文件格式不对");
                $('#collapse-file-error-hint').collapse();
                return false;
            } else {
            }
            //提交
            url = "frontaddSong";
            /**
             *    var data=$('#addSongFormId').serialize();
             *    序列化的方式,表单里有文件的时候就不行了,可以用FormData对象
             */
            var data = new FormData(document.getElementById("addSongFormId"));
            //var data = new FormData($('#addSongFormId'));
            $.ajax({
                type: "POST",
                url: url,
                data: data,
                processData: false,
                contentType: false,
                success: function (data) {
                    var res = JSON.parse(data);
                    if (res.status == 200) {
                        $('#collapse-file-error-hint').html(res.msg);
                        $('#collapse-file-error-hint').collapse()
                        alert("上传成功");
                        $("#UpModalCenter").modal('hide');
                        // window.location.reload();
                        $('#list-upload').load("uploadFrameLoad.do");
                    } else {
                        $('#collapse-file-error-hint').html(res.msg);
                        $('#collapse-file-error-hint').collapse()
                    }
                }
            });
            return false;
 
        });//处理上传 End
 
    });
</script>

后台代码:

    /**
     * 添加歌曲
     *
     * @param request
     * @param song
     * @return
     */
    @PostMapping(value = "frontaddSong")
    @ResponseBody
    public String addSong(HttpServletRequest request, String songAuthor,
                          Integer songLanguageType, MultipartFile song) {
        String name = song.getOriginalFilename();
        //歌曲名称需去掉.mp3的后缀
        String songName = name.substring(0, name.lastIndexOf("."));
        //这里上传至webapp下的track/song文件夹下
        String songAddress = "track/song/" + name;
        User user = (User) request.getSession().getAttribute("user");
        Song song1 = new Song(songName, songAddress, songLanguageType, 1,
                0, user.getUserId(), songAuthor, 0, 0);
        int result = songDao.insertOnlySong(song1);
        if (result > 0) {
            saveFile(song, request.getServletContext().getRealPath(songAddress));
            return ReturnMsg.msg(HttpServletResponse.SC_OK, "上传成功");
        } else {
            return ReturnMsg.msg(HttpServletResponse.SC_BAD_GATEWAY, "上传失敗");
        }
    }
 
    private void saveFile(MultipartFile multipartFile, String realFilePath) {
        try {
            //使用输入输出缓冲流提高上传效率
            InputStream fis = multipartFile.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(fis);
            FileOutputStream fos = new FileOutputStream(realFilePath);
            BufferedOutputStream bos = new BufferedOutputStream(fos);
            int size = 0;
            byte[] buffer = new byte[10240];
            while ((size = bis.read(buffer)) != -1) {
                bos.write(buffer, 0, size);
            }
            //刷新此缓冲的输出流,保证数据全部都能写出
            bos.flush();
            bis.close();
            bos.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
 
    }

文件下载

//download.do?songAddress=track/song/毛不易 - 无问.mp3&songId=290
  @RequestMapping(value = "download.do", method = { RequestMethod.GET})
  public void download(HttpServletRequest request,HttpServletResponse response,String songAddress,int songId) throws IOException {
    response.setContentType("audio/mp3");
    response.setHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode(System.currentTimeMillis()+"如果不想返回名称的话.mp3", "utf8"));
    BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());  
    InputStream bis=null;
    if(songAddress.contains("http")) {
      //在另外服务器的文件
      URL url = new URL(songAddress);  
            URLConnection uc = url.openConnection();  
      bis=new BufferedInputStream(uc.getInputStream());
    }else {
      //在服务器内部的文件
      songAddress=request.getServletContext().getRealPath(songAddress);
      bis = new BufferedInputStream(new FileInputStream(new File(songAddress)));
    }
    int len = 0;  
    while((len = bis.read()) != -1){  
            out.write(len);  
            out.flush();  
        }  
    out.close();
    bis.close();
  }

案例二:

读写指定路径的文件

public static void main(String[] args){
        /**
         * 1.先将文件中的内容读入到缓冲输入流中
         * 2.将输入流中的数据通过缓冲输出流写入到目标文件中
         * 3.关闭输入流和输出流
         */
        try {
            long begin=System.currentTimeMillis();
            FileInputStream fis=new FileInputStream("BISDemo.txt");
            BufferedInputStream bis=new BufferedInputStream(fis);
 
            FileOutputStream fos=new FileOutputStream("BOSDemo.txt");
            BufferedOutputStream bos=new BufferedOutputStream(fos);
 
            int size=0;
            byte[] buffer=new byte[10240];
            while((size=bis.read(buffer))!=-1){
                bos.write(buffer, 0, size);
            }
            //刷新此缓冲的输出流,保证数据全部都能写出
            bos.flush();
            bis.close();
            bos.close();
            long end=System.currentTimeMillis();
            System.out.println("使用缓冲输出流和缓冲输入流实现文件的复制完毕!耗时:"+(end-begin)+"毫秒");
        } catch (Exception e) {
                e.printStackTrace();
        }
    }

案例三:springmvc中后台如何接受上传文件方法

private void saveFile(MultipartFile multipartFile, String realFilePath) {
        try {
            InputStream fis = multipartFile.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(fis);
            FileOutputStream fos = new FileOutputStream(realFilePath);
            BufferedOutputStream bos = new BufferedOutputStream(fos);
            int size = 0;
            byte[] buffer = new byte[10240];
            while ((size = bis.read(buffer)) != -1) {
                bos.write(buffer, 0, size);
            }
            //刷新此缓冲的输出流,保证数据全部都能写出
            bos.flush();
            bis.close();
            bos.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
 
    }

案例四:异步上传文件

表单html

 <form id="addcropform" class="add-article-form" enctype="multipart/form-data">
                    <input type="hidden" value="${crop.id}" name="id">
                    <div class="col-md-9">
                        <h1 class="page-header">农作物编辑</h1>
                        <div class="form-group">
                            <p style="font-size: 16px;margin-bottom: 5px;">农作物名称</p>
                            <input type="text" id="title" name="title" value="${crop.title}" class="form-control"
                                   required="required" placeholder="名称">
                        </div>
                        <div class="form-group">
                            <label for="category-fname">农作物类别</label>
                            <select id="category-fname" class="form-control" name="typeid"
                                    style="width: 240px;margin-bottom: 10px">
                                <option value="">请选择</option>
                                <c:forEach items="${types}" var="t">
                                    <c:if test="${t.parentid==1}">
                                        <option value="${t.id}" ${crop.typeid==t.id?'selected' : ''}>${t.name}</option>
                                    </c:if>
                                </c:forEach>
                            </select>
                        </div>
                        <div class="form-group">
                            <p style="font-size: 16px;margin-bottom: 5px;">特性</p>
                            <input type="text" name="feature" value="${crop.feature}" class="form-control"
                                   placeholder="特性"
                                   required="required">
                        </div>
                        <div class="form-group">
                            <p style="font-size: 16px;margin-bottom: 5px;">生长环境</p>
                            <input type="text" name="environment" value="${crop.environment}" class="form-control"
                                   placeholder="生长环境"
                                   required="required">
                        </div>
                        <div class="form-group">
                            <p style="font-size: 16px;margin-bottom: 5px;">产地</p>
                            <input type="text" name="location" value="${crop.location}" class="form-control"
                                   placeholder="产地"
                                   required="required">
                        </div>
                        <div class="form-group">
                            <p style="font-size: 16px;margin-bottom: 5px;">图片</p>
                            <img src="<%=path %>${crop.img}" style="width: 80px;">
                            <input type="file" name="img" value="<%=path %>${crop.img}">
                        </div>
 
                        <div class="form-group">
                            <div id="editor" class="layui-input-block" style="background: white;">
                                <p>${crop.info}</p>
                            </div>
                            <div class="layui-input-block">
                                <textarea style="width:700px;height:100px;visibility:hidden;" name="info"
                                          id="text1"></textarea>
                            </div>
                            <script type="text/javascript">
                                var E = window.wangEditor;
                                var editor = new E('#editor');
                                // 或者 var editor = new E( document.getElementById('editor') )
                                editor.customConfig.uploadImgShowBase64 = true;  // 使用 base64 保存图片
                                var $text1 = $('#text1')
                                editor.customConfig.onchange = function (html) {
                                    // 监控变化,同步更新到 textarea
                                    $text1.val(html)
                                }
                                editor.create();
                                $text1.val(editor.txt.html());
                            </script>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <h1 class="page-header">操作</h1>
                        <div class="add-article-box-footer">
                            <button class="btn btn-primary" type="button" onclick="addCrop()" name="submit">发布
                            </button>
                        </div>
                    </div>
                </form>

js代码

<script>
    function addCrop() {
        var title = $("#title").val();
        if (!title) {
            alert("名称不能为空");
            return;
        }
        var formdata = new FormData($("#addcropform")[0]);
        $.ajax({
            type: "POST",//方法类型
            dataType: "json",//预期服务器返回的数据类型
            url: "/admin/addcrop",//url
            data: formdata,
            async: false,
            cache: false,
            contentType: false,
            processData: false,
            success: function (result) {
                console.log(result);//打印服务端返回的数据(调试用)
                if (result.status == 200) {
                    alert("提交成功");
                    window.location.reload();
                } else {
                    alert(result.msg);
                }
            },
            error: function () {
                alert("异常!");
            }
        });
    }
</script>

后端代码

@ResponseBody
    @PostMapping("/addcrop")
    public Result addcrop(Integer id, HttpServletRequest request, String title, String info,
                          Integer typeid, String feature, String location,
                          String environment, @RequestParam("img") MultipartFile img) throws IOException {
        if (id != null) {
            //修改
            String fileName = null;
            if (!img.isEmpty()) {
                //根据时间戳创建新的文件名,这样即便是第二次上传相同名称的文件,也不会把第一次的文件覆盖了
                fileName = System.currentTimeMillis() + img.getOriginalFilename();
                //通过req.getServletContext().getRealPath("") 获取当前项目的真实路径,然后拼接前面的文件名,这个是web项目情况 如果是jar项目,不能使用这个
                String destFileName = request.getServletContext().getRealPath("") + "upload" + File.separator + fileName;
                File destFile = new File(destFileName);
                //把浏览器上传的文件复制到希望的位置
                img.transferTo(destFile);
                //6.把文件名放在model里,以便后续显示用
            }
            Crop crop=null;
            if(img.getOriginalFilename().equals("")){
                 crop = new Crop(id, title, null, info, new Date(),
                        typeid, feature, location, environment);
            }else{
                 crop = new Crop(id, title, "/upload/" + fileName, info, new Date(),
                        typeid, feature, location, environment);
            }
 
            cropMapper.updateByPrimaryKey(crop);
            return new Result(200);
        } else {//添加
            String fileName = null;
            if (!img.isEmpty()) {
                //根据时间戳创建新的文件名,这样即便是第二次上传相同名称的文件,也不会把第一次的文件覆盖了
                fileName = System.currentTimeMillis() + img.getOriginalFilename();
                //通过req.getServletContext().getRealPath("") 获取当前项目的真实路径,然后拼接前面的文件名
                String destFileName = request.getServletContext().getRealPath("") + "upload" + File.separator + fileName;
                File destFile = new File(destFileName);
                //把浏览器上传的文件复制到希望的位置
                img.transferTo(destFile);
            }
            Crop crop = new Crop(id, title, "/upload/" + fileName, info, new Date(),
                    typeid, feature, location, environment);
            cropMapper.insert(crop);
            return new Result(200);
        }
    }

大文件上传

https://mp.weixin.qq.com/s/h2ZxO1VDDVQKd4LxRFmcDw


相关文章
|
Java 开发工具
【Azure Storage Account】Java Code访问Storage Account File Share的上传和下载代码示例
本文介绍如何使用Java通过azure-storage-file-share SDK实现Azure文件共享的上传下载。包含依赖引入、客户端创建及完整示例代码,助你快速集成Azure File Share功能。
870 6
基于JavaWeb的销售管理系统设计系统
本系统基于Java、MySQL、Spring Boot与Vue.js技术,构建高效、可扩展的销售管理平台,实现客户、订单、数据可视化等全流程自动化管理,提升企业运营效率与决策能力。
|
SQL 前端开发 Java
JavaWeb 学习日记案例详解及 javaweb 完整项目案例实战指南
本文介绍了一个基于Spring Boot的JavaWeb企业员工管理系统完整案例,涵盖部门管理、员工管理、登录、异常处理、事务管理及AOP等核心功能实现,结合CSDN相关技术文章,提供详细技术方案与应用实例,适合JavaWeb开发者学习与参考。
889 0
|
存储 人工智能 Java
java之通过Http下载文件
本文介绍了使用Java实现通过文件链接下载文件到本地的方法,主要涉及URL、HttpURLConnection及输入输出流的操作。
950 0
|
存储 安全 算法
Java 集合面试题 PDF 下载及高频考点解析
本文围绕Java集合面试题展开,详细解析了集合框架的基本概念、常见集合类的特点与应用场景。内容涵盖`ArrayList`与`LinkedList`的区别、`HashSet`与`TreeSet`的对比、`HashMap`与`ConcurrentHashMap`的线程安全性分析等。通过技术方案与应用实例,帮助读者深入理解集合类的特性和使用场景,提升解决实际开发问题的能力。文末附带资源链接,供进一步学习参考。
454 4
|
Linux 网络安全 Docker
尼恩一键开发环境: vagrant+java+springcloud+redis+zookeeper镜像下载(&制作详解)
尼恩提供了一系列文章,旨在帮助开发者轻松搭建一键开发环境,涵盖Java分布式、高并发场景下的多种技术组件安装与配置。内容包括但不限于Windows和CentOS虚拟机的安装与排坑指南、MySQL、Kafka、Redis、Zookeeper等关键组件在Linux环境下的部署教程,并附带详细的视频指导。此外,还特别介绍了Vagrant这一虚拟环境部署工具,
尼恩一键开发环境: vagrant+java+springcloud+redis+zookeeper镜像下载(&制作详解)
java引入本地 MultipartFile 实现多部分文件上传
在Java中,`MultipartFile`通常用于处理通过HTML表单上传的文件。但在某些情况下,需要直接从本地文件系统获取文件并上传。本文介绍如何创建一个实现了`MultipartFile`接口的本地类`LocalMultipartFile`,将本地文件转换为`MultipartFile`对象,简化文件上传流程。此方法适用于批量上传等场景,避免了表单上传的复杂性。代码示例展示了如何实现和使用该类进行文件上传操作。作者:华科云商小彭。链接:[稀土掘金](https://juejin.cn/post/7377559533785530431)。
964 18
|
JSON 网络协议 安全
【Java】(10)进程与线程的关系、Tread类;讲解基本线程安全、网络编程内容;JSON序列化与反序列化
几乎所有的操作系统都支持进程的概念,进程是处于运行过程中的程序,并且具有一定的独立功能,进程是系统进行资源分配和调度的一个独立单位一般而言,进程包含如下三个特征。独立性动态性并发性。
771 1
|
JSON 网络协议 安全
【Java基础】(1)进程与线程的关系、Tread类;讲解基本线程安全、网络编程内容;JSON序列化与反序列化
几乎所有的操作系统都支持进程的概念,进程是处于运行过程中的程序,并且具有一定的独立功能,进程是系统进行资源分配和调度的一个独立单位一般而言,进程包含如下三个特征。独立性动态性并发性。
685 1
|
数据采集 存储 弹性计算
高并发Java爬虫的瓶颈分析与动态线程优化方案
高并发Java爬虫的瓶颈分析与动态线程优化方案