Java:实现文件的上传和下载

发布时间 2023-12-12 10:08:11作者: Xproer-松鼠

1、实现文件上传功能
1. 配置文件:

添加配置文件spring-mvc.xml,配置multipartResolver,实现文件上传和下载的功能。
<!-- 文件上传配置 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="104857600"/>
<property name="defaultEncoding" value="UTF-8"/>
</bean>
<!-- 视图解析器 -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>

这段代码是一个Spring MVC的Controller方法,用于处理文件上传的POST请求。具体解析如下:

@RequestMapping注解指定了请求的URL为"/file",请求方法为POST。

方法参数中的@RequestParam注解指定了上传的文件参数名为"file",并将其绑定到MultipartFile类型的file变量中。

判断上传的文件是否为空,如果不为空则执行文件保存操作。

文件保存的路径为"/path/to/save/file/" + 文件名,其中"/path/to/save/file/"需要根据实际情况修改。

通过File类创建目标文件对象dest,并将上传的文件内容保存到该文件中。

如果保存过程中出现异常,则打印异常信息。

最后返回一个重定向到"/success.jsp"页面的字符串。

2. 实现上传文件的Controller:

使用@RequestParam注解获取上传的文件,并保存到指定的文件夹中。
@Controller
@RequestMapping("/upload")
public class UploadController {
@RequestMapping(value = "/file", method = RequestMethod.POST)
public String uploadFile(@RequestParam("file") MultipartFile file) {
if (!file.isEmpty()) {
try {
String filePath = "/path/to/save/file/" + file.getOriginalFilename();
File dest = new File(filePath);
file.transferTo(dest);
} catch (IOException e) {
e.printStackTrace();
}
}
return "redirect:/success.jsp";
}
}

2、实现文件下载功能
<!-- 文件下载配置 -->
<bean id="downloadView" class="com.islunatic.DownloadView"/>

<!-- 视图解析器 -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
实现下载文件的View:
使用HttpServletResponse的outputStream将文件写入到response中,实现文件下载。
public class DownloadView extends AbstractView {

protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request,
HttpServletResponse response) throws Exception {
String filePath = model.get("filename").toString();
File file = new File(filePath);
response.setContentType(getContentType());
response.setContentLength((int) file.length());
response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");
OutputStream out = response.getOutputStream();
InputStream in = new FileInputStream(file);
byte[] buffer = new byte[4096];
int length;
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
in.close();
out.flush();
}
}

这段代码是一个Spring MVC的控制器,用于处理文件下载请求。具体解析如下:

@Controller和@RequestMapping("/download")注解表示这是一个控制器类,处理以/download开头的请求。

@RequestMapping(value = "/file", method = RequestMethod.GET)注解表示该方法处理以/download/file开头的GET请求。

HttpServletRequest和HttpServletResponse参数分别表示请求和响应对象。

String filePath = "/path/to/the/file/to/download";表示要下载的文件路径。

File file = new File(filePath);创建一个File对象,表示要下载的文件。

if (file.exists()) {判断文件是否存在。

Map<String, Object> model = new HashMap<>();创建一个Map对象,用于存储模型数据。

model.put("filename", filePath);将文件路径存储到模型数据中,键为"filename"。

return new ModelAndView("downloadView", model);返回一个ModelAndView对象,表示要下载的文件视图。

"downloadView"表示要使用的视图名称,Spring会根据该名称查找对应的视图。

model表示要传递给视图的模型数据。

return null;如果文件不存在,则返回null。

实现下载文件的Controller:
通过ModelAndView返回DownloadView,下载指定路径的文件。
@Controller
@RequestMapping("/download")
public class DownloadController {

@RequestMapping(value = "/file", method = RequestMethod.GET)
public ModelAndView downloadFile(HttpServletRequest request, HttpServletResponse response) {
String filePath = "/path/to/the/file/to/download";
File file = new File(filePath);
if (file.exists()) {
Map<String, Object> model = new HashMap<>();
model.put("filename", filePath);
return new ModelAndView("downloadView", model);
}
return null;
}
}

 

参考文章:http://blog.ncmem.com/wordpress/2023/12/12/java%ef%bc%9a%e5%ae%9e%e7%8e%b0%e6%96%87%e4%bb%b6%e7%9a%84%e4%b8%8a%e4%bc%a0%e5%92%8c%e4%b8%8b%e8%bd%bd/

欢迎入群一起讨论