把上传并下载到项目中ssm
时间: 2024-03-23 17:37:50 浏览: 56
要将上传和下载功能集成到SSM项目中,可以按照以下步骤操作:
1. 在项目中添加文件上传和下载的相关依赖包,例如commons-fileupload和commons-io。
2. 编写上传和下载的Controller层代码,可以参考以下示例代码:
上传文件:
```
@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
@ResponseBody
public String uploadFile(HttpServletRequest request, HttpServletResponse response) {
String result = "";
try {
// 获取上传的文件
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
MultipartFile file = multipartRequest.getFile("file");
// 获取文件名
String fileName = file.getOriginalFilename();
// 拼接文件存储的路径
String filePath = request.getSession().getServletContext().getRealPath("/") + "upload/";
File fileDir = new File(filePath);
if (!fileDir.exists()) {
fileDir.mkdirs();
}
// 将上传的文件保存到指定路径
file.transferTo(new File(filePath + fileName));
result = "success";
} catch (Exception e) {
result = "error";
e.printStackTrace();
}
return result;
}
```
下载文件:
```
@RequestMapping(value = "/downloadFile", method = RequestMethod.GET)
public void downloadFile(HttpServletRequest request, HttpServletResponse response) {
String fileName = "test.txt";
String filePath = request.getSession().getServletContext().getRealPath("/") + "upload/";
try {
// 设置响应头
response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
// 获取要下载的文件流
InputStream inputStream = new FileInputStream(filePath + fileName);
OutputStream outputStream = response.getOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, len);
}
inputStream.close();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
```
3. 在页面中添加上传和下载的相关代码,例如:
上传文件:
```
<form id="uploadForm" action="uploadFile" method="post" enctype="multipart/form-data">
<input type="file" name="file"/>
<input type="button" value="上传" onclick="uploadFile()"/>
</form>
<script>
function uploadFile() {
$.ajax({
type: "POST",
url: "uploadFile",
data: new FormData($("#uploadForm")[0]),
async: false,
cache: false,
contentType: false,
processData: false,
success: function (data) {
alert(data);
},
error: function () {
alert("上传失败!");
}
});
}
</script>
```
下载文件:
```
<a href="downloadFile">下载</a>
```
4. 运行项目,测试上传和下载功能是否正常。
阅读全文