使用SSM框架与layui实现文件上传与下载
时间: 2024-05-13 12:18:43 浏览: 141
基于SSM文件的上传和下载
文件上传与下载是Web应用程序中常用的功能,使用SSM框架与layui可以轻松实现这些功能。
1. 实现文件上传
(1)在页面中添加上传文件的表单
```html
<form method="post" action="upload" enctype="multipart/form-data">
<div class="layui-form-item">
<label class="layui-form-label">上传文件</label>
<div class="layui-input-block">
<input type="file" name="file" lay-verify="required" class="layui-upload-file">
</div>
</div>
<div class="layui-form-item">
<div class="layui-input-block">
<button class="layui-btn" lay-submit lay-filter="upload">上传</button>
</div>
</div>
</form>
```
(2)在Controller中处理上传请求
```java
@RequestMapping("/upload")
@ResponseBody
public String upload(@RequestParam("file") MultipartFile file) {
if (file.isEmpty()) {
return "上传文件不能为空";
}
String fileName = file.getOriginalFilename();
String filePath = "D:\\upload\\";
File dest = new File(filePath + fileName);
try {
file.transferTo(dest);
return "文件上传成功";
} catch (IOException e) {
e.printStackTrace();
}
return "文件上传失败";
}
```
2. 实现文件下载
(1)在页面中添加下载链接
```html
<a href="download?fileName=xxx.txt">下载文件</a>
```
(2)在Controller中处理下载请求
```java
@RequestMapping("/download")
public void download(HttpServletResponse response, @RequestParam("fileName") String fileName) throws IOException {
String filePath = "D:\\upload\\";
File file = new File(filePath + fileName);
if (file.exists()) {
response.setContentType("application/force-download");
response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
byte[] buffer = new byte[1024];
FileInputStream fis = null;
BufferedInputStream bis = null;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
OutputStream os = response.getOutputStream();
int i = bis.read(buffer);
while (i != -1) {
os.write(buffer, 0, i);
i = bis.read(buffer);
}
System.out.println("文件下载成功");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null) {
bis.close();
}
if (fis != null) {
fis.close();
}
}
}
}
```
以上就是使用SSM框架与layui实现文件上传与下载的全部内容。
阅读全文