SpringBoot项目 前后端分离 ajax附件上传下载

6 篇文章 0 订阅

目录

前台界面 

上传 

下载 

前台代码

后台项目结构

后台主要代码

下载

调整对下载不存在文件的处理

效果

代码 


前台界面 

上传 

下载 

前台代码

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>附件上传、下载</title>
    <script type="text/javascript" src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
</head>
<body>
    <br />
    <p>
        附件上传、下载</p>
    <br />
    <form enctype="multipart/form-data" id="upload">
    文件:<input type="file" name="file" id="file" />
    <input type="button" value="上传" onclick="fn_upload()" />
    </form>
    <br />
    <input type="text" id="file_name" style="width: 296px;" />
    <input type="button" value="下载" onclick="fn_download()" />
    <script type="text/javascript">

        function fn_download() {
            var file_name = $("#file_name").val();
            if (file_name == "") {
                alert("请输入下载文件名称!");
                $("#file_name").focus();
                return;
            }

            var url = "http://127.0.0.1:8080/file/download?file_name=" + file_name;
            var a = document.createElement("a");
            a.href = url;
            a.click();

        }

        function fn_upload() {

            var file = $('#file')[0].files[0];
            if (file == undefined) {
                alert("请选择文件!");
                return;
            }
            var formData = new FormData($('#upload')[0]);
            formData.append('file', file);
            formData.append('fid', "10"); //其他参数  比如外键ID

            jQuery.support.cors = true;
            $.ajax({
                url: "http://127.0.0.1:8080/file/upload",
                type: "POST",
                data: formData,
                processData: false,    //不需要对数据做任何预处理
                contentType: false,    //不设置数据格式
                timeout: 5000,
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    if (XMLHttpRequest.responseText == "") {
                        alert("请求超时,请检查网络!", { icon: 2 });
                    } else {
                        alert(XMLHttpRequest.statusText, { icon: 2 });
                    }
                },
                success: function (d) {
                    if (d.code == 0) {
                        alert("上传成功!");
                        $("#file_name").val(d.data)
                    } else {
                        alert("删除失败" + d.msg);
                    }
                }
            });

        }

    </script>
</body>
</html>

后台项目结构

后台主要代码

package com.lxw.uploaddownload.controller;


import com.lxw.uploaddownload.common.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;

@RestController
@RequestMapping("/file")
public class FileController {

    @Value("${filePath}")
    private String filePath;

    private static final Logger logger = LoggerFactory.getLogger(FileController.class);


    //上传文件
    @PostMapping("/upload")
    @ResponseBody
    public Response uploadFile(@RequestParam("file") MultipartFile file, @RequestParam("fid") Integer fid, HttpServletResponse response)  {

        if (file.isEmpty()) {
            return new Response().error("上传失败,请选择文件");
        }
        // 获得提交的文件名
        String fileName = file.getOriginalFilename();
        // 获取文件输入流
        //InputStream ins = file.getInputStream();
        // 获取文件类型
        //String contentType = file.getContentType();

        //加个时间戳,尽量避免文件名称重复
        fileName = new SimpleDateFormat("yyyyMMddHHmmssSSSS").format(new Date()) + "_" + fileName;

        File dest = new File(filePath + fileName);
        if (!dest.getParentFile().exists()) { //判断文件父目录是否存在
            dest.getParentFile().mkdir();
        }
        try {
            file.transferTo(dest);
            //logger.info("上传成功");
            return new Response().success(fileName);
        } catch (Exception e) {
            //logger.error(e.getMessage());
            return new Response().error("上传失败");
        }
    }

    //下载文件
    @GetMapping(value = "/download")
    public void downloadFile(@RequestParam(name = "file_name") String fileName,
                             HttpServletRequest request,
                             HttpServletResponse response) throws IOException {
        //logger.info("download....file_name:" + fileName);

        File file = new File(filePath + "/" + fileName);
        if (file.exists()) { //判断文件是否存在
            response.setContentType("application/force-download");
            response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
            byte[] buffer = new byte[1024];
            FileInputStream fis = null; //文件输入流
            BufferedInputStream bis = null;
            OutputStream os = null; //输出流
            try {
                os = response.getOutputStream();
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer);
                    i = bis.read(buffer);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            logger.info("----------file download" + fileName);
            try {
                bis.close();
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else{
            response.setStatus(404);
        }
    }

}
 

package com.lxw.uploaddownload.controller;


import com.lxw.uploaddownload.common.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;

@RestController
@RequestMapping("/file")
public class FileController {

    @Value("${filePath}")
    private String filePath;

    private static final Logger logger = LoggerFactory.getLogger(FileController.class);


    //上传文件
    @PostMapping("/upload")
    @ResponseBody
    public Response uploadFile(@RequestParam("file") MultipartFile file, @RequestParam("fid") Integer fid, HttpServletResponse response)  {

        if (file.isEmpty()) {
            return new Response().error("上传失败,请选择文件");
        }
        // 获得提交的文件名
        String fileName = file.getOriginalFilename();
        // 获取文件输入流
        //InputStream ins = file.getInputStream();
        // 获取文件类型
        //String contentType = file.getContentType();

        //加个时间戳,尽量避免文件名称重复
        fileName = new SimpleDateFormat("yyyyMMddHHmmssSSSS").format(new Date()) + "_" + fileName;

        File dest = new File(filePath + fileName);
        if (!dest.getParentFile().exists()) { //判断文件父目录是否存在
            dest.getParentFile().mkdir();
        }
        try {
            file.transferTo(dest);
            //logger.info("上传成功");
            return new Response().success(fileName);
        } catch (Exception e) {
            //logger.error(e.getMessage());
            return new Response().error("上传失败");
        }
    }

    //下载文件
    @GetMapping(value = "/download")
    public void downloadFile(@RequestParam(name = "file_name") String fileName,
                             HttpServletRequest request,
                             HttpServletResponse response) throws IOException {
        //logger.info("download....file_name:" + fileName);

        File file = new File(filePath + "/" + fileName);
        if (file.exists()) { //判断文件是否存在
            response.setContentType("application/force-download");
            response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
            byte[] buffer = new byte[1024];
            FileInputStream fis = null; //文件输入流
            BufferedInputStream bis = null;
            OutputStream os = null; //输出流
            try {
                os = response.getOutputStream();
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer);
                    i = bis.read(buffer);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            logger.info("----------file download" + fileName);
            try {
                bis.close();
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else{
            response.setStatus(404);
        }
    }

}

下载

Demo下载

调整对下载不存在文件的处理

效果

代码 

        if (file.exists()) { //判断文件是否存在
             //
        } else {
            try {
                response.setContentType("text/html; charset=UTF-8"); //转码
                PrintWriter out = response.getWriter();
                out.flush();
                out.println("文件不存在或已经被删除!");
            } catch (IOException e) {
                // logger.error("下载文件出错:" + e);
            }
        }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

天天代码码天天

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值