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

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请求。具体解析如下:

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

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

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

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

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

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

  7. 最后返回一个重定向到"/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的控制器,用于处理文件下载请求。具体解析如下:

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

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

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

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

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

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

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

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

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

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

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

  12. 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;
    }
}

  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

IsLuNaTiC

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值