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

上传

下载

前台代码
<!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);
}
}
}
调整对下载不存在文件的处理
效果

代码
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);
}
}
SpringBoot项目 前后端分离 ajax附件上传下载的更多相关文章
- 仵航说 前后端分离,文件上传下载(springBoot+vue+elementUI)仵老大
1.介绍 本文主要是介绍前后端分离的上传下载,后端使用的是SpringBoot,持久层用的是mybatis-plus,前端用的Vue,UI用的elementUI,测试了一下,文本,图片,excel ...
- Ueditor 前后端分离实现文件上传到独立服务器
关于Ueditor 前后端分离实现文件上传到独立服务器,在网上搜索确实遇到大坑,不过还好遇到了 虚若影 最终实现了,在此感谢!虚若影的原文博客网址:http://www.cnblogs.com/hpn ...
- UEditor实现前后端分离时单图上传
首先,需要下载部署ueditor相关代码,可以参考一篇简单的博客,这里不再赘述: 环境搭建好后,我们先简单使用一下,启动http://web.yucong.com:8080/ueditor/index ...
- 关于Ueditor 前后端分离实现文件上传到独立服务器的问题 望大神们赐教
最近,由于网站实现多台服务器负载均衡,导致编辑器上传文件需要同步,可是使用同步软件太慢,不太现实,所以想到实现编辑器上传文件直接上传到独立文件服务器.可是没想到遇到坑了. 1.在本地IIS 中添加网站 ...
- 前后端分离--ajaxUpload异步上传文件成功,前端获取数据却失败的解决方案
转载:https://blog.csdn.net/baidu_32809053/article/details/78709951
- Springboot+vue前后端分离项目,poi导出excel提供用户下载的解决方案
因为我们做的是前后端分离项目 无法采用response.write直接将文件流写出 我们采用阿里云oss 进行保存 再返回的结果对象里面保存我们的文件地址 废话不多说,上代码 Springboot 第 ...
- SpringBoot+Vue前后端分离项目,在过滤器取值为Null
SpringBoot+Vue前后端分离项目,在过滤器取值为Null 是因为SessionID的问题,因为axios每次的请求都是一次新的sessionId,所以只需要在main.js下配置如下 axi ...
- springboot+apache前后端分离部署https
目录 1. 引言 2. 了解https.证书.openssl及keytool 2.1 https 2.1.1 什么是https 2.1.2 https解决什么问题 2.2 证书 2.2.1 证书内容 ...
- SpringBoot+Vue前后端分离,使用SpringSecurity完美处理权限问题
原文链接:https://segmentfault.com/a/1190000012879279 当前后端分离时,权限问题的处理也和我们传统的处理方式有一点差异.笔者前几天刚好在负责一个项目的权限管理 ...
- Vue+ElementUI+Springboot实现前后端分离的一个demo
目录 1.前期准备 2.创建一个vue项目 3.vue前端 4.java后端 5.启动 5.1.启动vue项目 5.2.启动后端 6.效果 7.总结 8.参考资料 vue官方文档:介绍 - Vue.j ...
随机推荐
- Oracle字符串行专列(字符串聚合技术)
原文链接:http://oracle-base.com/articles/misc/string-aggregation-techniques.php 1 String Aggregation ...
- Java使用正则表达式判断字符串中是否包含某子字符串
需求: 给定一个字符串s,判断当s中包含"tree fiddy"或"3.50"或"three thirty"子字符串返回true,否则返回f ...
- 使用winsw将jar包注册成windows服务
使用winsw将jar包注册成windows服务 注:exe文件作用:使用winsw将jar包注册成windows服务(下载地址https://github.com/winsw/winsw/relea ...
- 【Azure 微服务】新创建的Service Fabric集群,如何从本地机器上连接到Service Fabric Explorer(Service Fabric状态/错误查看工具)呢?
问题描述 当在Azure中成功创建一个Service Fabric Cluster 服务后,我们能够在它的Overview页面中发现 Service Fabric Explorer的终结点,但是打开后 ...
- 【Azure 存储服务】如何查看Storage Account的删除记录,有没有接口可以下载近1天删除的Blob文件信息呢?
问题描述 如何查看Storage Account的删除记录,有没有接口可以下载近1天删除的Blob文件信息呢?因为有时候出现误操作删除了某些Blob文件,想通过查看删除日志来定位被删除的文件信息. 问 ...
- 隐私计算在释放万亿美元 SaaS 市场的重要作用
PrimiHub一款由密码学专家团队打造的开源隐私计算平台,专注于分享数据安全.密码学.联邦学习.同态加密等隐私计算领域的技术和内容. 过去十年间数字领域经历了一场颠覆性的转变.这一演变的前沿是软件即 ...
- 18 Codeforces Round 853 (Div. 2)C. Serval and Toxel's Arrays(算贡献)
C. Serval and Toxel's Arrays 这种题目做多了应该很容易从贡献的角度去考虑了. 考虑当前版本对答案的贡献,首先这个版本和其他版本取交集至少会包含它本身所以直接先把\(i * ...
- Linux 系统错误码 errno 剖析
一.errno 介绍 1.1 errno 简介 Linux 中系统调用的错误都存储于错误码 errno 中.errno 由操作系统维护,存储就近发生的错误,即下一次的错误码会覆盖掉上一次的错误. er ...
- 快速带你入门css
css复习笔记 1. css样式值 1.1 文字样式 1 p{ 2 font-size: 30px;/*设置文字大小*/ 3 font-weight: bold;/*文字加粗*/ 4 font-sty ...
- 使用@RequestBody注解踩的坑
一.问题由来 最近在和前端调试一个自己写的接口时,频频出现问题,让我很是烦恼.因此写下这篇博文来记录开发中遇到的一些问题.第一个问题是 前端页面传递参数后,后台不能正常接收参数.我写好接口以后,通过s ...