ssm 前端上传文件,java后台接收文件并存储到mysql数据库(绝对路径)和下载
程序员文章站
2022-07-10 17:48:01
准备首先导入两个jar包,下方是maven依赖,版本可自己选 commons-io commons-io 1.4
准备
首先导入两个jar包,下方是maven依赖,版本可自己选
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>1.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.2</version>
</dependency>
html
<form name="form" action="" enctype="multipart/form-data"
method="post">
<input type="file" name="uploadFile" id="upload">
<button type="submit" onclick="formSave()">保存</button>
</form>
<script>
function formSave() {
document.form.action="${pageContext.request.contextPath}/test/save.do";
}
</script>
java后端
@RequestMapping("/save.do")
public void save(Contract contract, @RequestParam("uploadFile") MultipartFile file, HttpServletRequest request) throws Exception {
String trueName = file.getOriginalFilename();
String path = "d:/"; //自己设置一个路径
File file1 = new File(path + trueName);
String uploadURL = path + trueName;
// 判断当前文件父级文件夹是否存在,如果不存在,就创建文件夹
if (!file1.getParentFile().exists()) {
file1.mkdirs();
}
try {
// 上传文件,核心功能
file.transferTo(file1);
} catch (IOException e) {
e.printStackTrace();
}
}
几个注意点
接下来就是写service层和dao层,很简单,普通的增删改查(略)
下载
<a href="${pageContext.request.contextPath}/contract/downLoadAppendices.do?id=${contract.ID}">下载</a>
@RequestMapping("/downLoadAppendices.do")
public void downLoadAppendices(HttpServletRequest request,HttpServletResponse response) throws IOException {
//前端传id值,根据id值查出数据库字段中的地址字符串
String id = request.getParameter("id");
String path = contractService.downLoadAppendices(id);
// 修改文件名的编码格式
String fName = path.trim();
String fileName = fName.substring(fName.lastIndexOf("/")+1);
ServletContext servletContext = request.getServletContext();
FileInputStream fis = new FileInputStream(path);
//MIME类型:在互联网通信过程中定义的一种文件数据类型
String mimeType = servletContext.getMimeType(fileName);
response.setHeader("content-type",mimeType);
response.setHeader("content-disposition","attachment;filename="+fileName);
ServletOutputStream sos = response.getOutputStream();
byte[] buff = new byte[1024];
int len = 0;
while((len=fis.read(buff))!=-1){
sos.write(buff,0,len);
}
fis.close();
}
本文地址:https://blog.csdn.net/qq_29468977/article/details/109629682