springMVC文件上传和下载(简单案例)

这篇文章,我们将来讲一讲SpringMVC如何实现文件的上传操作。

一、文件上传 🌹

        1、导入相关依赖 

<dependency>
  <groupId>commons-fileupload</groupId>
  <artifactId>commons-fileupload</artifactId>
  <version>1.3.1</version>
</dependency>
<dependency>
  <groupId>commons-io</groupId>
  <artifactId>commons-io</artifactId>
  <version>2.4</version>
</dependency>

        2、准备jsp页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <meta charset="UTF-8">
    <title>上传页面</title>
</head>
<body>
    <h3>文件上传</h3>

    <form id="addForm"  action="upload" method="post" enctype="multipart/form-data">
        选择文件:<input type="file" name="file" width="120px">
        <input type="submit" value="上传">
    </form>

    <c:if test="${url!=null}">
        <img src="${pageContext.request.contextPath}/images/${url}" height="200px" width="200px" />
        <a href="down?filename=${url}">下载</a>
    </c:if>
</body>
</html>
  • 截图 

  • 运行结果

        3、编写Controller

package com.cskt.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

/**
 * @Description TODO
 * @Author Yii_oo
 * @CreateDate 2023-08-31 11:04
 * @Version 1.0
 * @ClassDesc 文件上传和下载
 */
@Controller
public class UploadController {

    /**
     * 文件上传功能
     * @param file
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/upload",method = RequestMethod.POST)
    public ModelAndView upload(@RequestParam("file")MultipartFile file, HttpServletRequest request ,ModelAndView modelAndView) throws IOException{
        // 图片存放文件夹位置     image你想放在项目的哪个文件夹下
        String rootPath = request.getSession().getServletContext().getRealPath("images");
        // 上传文件的原始名称
        String originalFileName = file.getOriginalFilename();
        // 新文件名称
        File newFile = new File(rootPath + File.separator + File.separator + originalFileName);
        // 判断目标文件所在目录是否存在
        if (!newFile.getParentFile().exists()) {
            //如果目标文件所在目录不存在,则创建父目录
            newFile.getParentFile().mkdirs();
        }
        file.transferTo(newFile);
        System.out.println(newFile);  //因为newFile是绝对路径,前端的img需要相对路径
        String filePath=newFile.toString();
        //截取相对路径
        String fileName = filePath.substring(filePath.lastIndexOf("\\")+1);
        System.out.println(fileName);
        modelAndView.addObject("url",fileName);
        modelAndView.setViewName("upload");
        return modelAndView;
    }


    /**
     * 文件下载功能
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping("/down")
    public void down(HttpServletRequest request, HttpServletResponse response) throws Exception{
        String filename = request.getParameter("filename");
        System.out.println(filename);
        //模拟文件,myfile.txt为需要下载的文件
        String fileName = request.getSession().getServletContext().getRealPath("images")+"/"+filename;
        //获取输入流
        InputStream bis = new BufferedInputStream(new FileInputStream(new File(fileName)));
        //假如以中文名下载的话
        // String filename = "下载文件.txt";
        //转码,免得文件名中文乱码
        filename = URLEncoder.encode(filename,"UTF-8");
        //设置文件下载头
        response.addHeader("Content-Disposition", "attachment;filename=" + filename);
        //1.设置文件ContentType类型,这样设置,会自动判断下载文件类型
        response.setContentType("multipart/form-data");
        BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
        int len = 0;
        while((len = bis.read()) != -1){
            out.write(len);
            out.flush();
        }
        out.close();
    }
}

              4、运行结果

 就完成了!

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
实现本地文件的上下载查看可以通过Spring MVC中的MultipartResolver来实现文件,通过response.getOutputStream()来实现文件下载和查看。 1. 文件 在Spring MVC中,实现文件需要使用MultipartResolver来处理上文件。MultipartResolver是一个接口,它定义了处理multipart请求的方法。Spring提供了两个实现类:CommonsMultipartResolver和StandardServletMultipartResolver。 在使用CommonsMultipartResolver时,需要在spring配置文件中添加以下配置: ``` <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize" value="10485760"/> </bean> ``` 其中,maxUploadSize属性定义了上文件大小限制。在这个例子中,最大上文件大小为10MB。 在Controller中,使用MultipartFile类来接收上文件: ``` @RequestMapping(value = "/upload", method = RequestMethod.POST) public String upload(@RequestParam("file") MultipartFile file) { if (!file.isEmpty()) { try { byte[] bytes = file.getBytes(); // 保存文件到本地 File localFile = new File("/path/to/save/file/" + file.getOriginalFilename()); FileOutputStream fos = new FileOutputStream(localFile); fos.write(bytes); fos.close(); // 保存成功 return "redirect:/success"; } catch (IOException e) { e.printStackTrace(); } } // 保存失败 return "redirect:/error"; } ``` 其中,@RequestParam("file")注解用于指定接收的文件参数名。 2. 文件下载和查看 在Controller中,使用response.getOutputStream()方法来实现文件下载和查看: ``` @RequestMapping(value = "/download/{filename}", method = RequestMethod.GET) public void download(@PathVariable("filename") String filename, HttpServletResponse response) { try { // 设置下载文件的响应头 response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment; filename=" + filename); // 获取文件输入流 FileInputStream fis = new FileInputStream("/path/to/file/" + filename); // 获取响应输出流 ServletOutputStream sos = response.getOutputStream(); // 将文件写入响应输出流 byte[] buffer = new byte[1024]; int len; while ((len = fis.read(buffer)) != -1) { sos.write(buffer, 0, len); } // 关闭流 sos.close(); fis.close(); } catch (IOException e) { e.printStackTrace(); } } ``` 其中,@PathVariable("filename")注解用于获取下载文件名。 如果需要在浏览器中查看文件,可以将响应头的Content-Type设置为文件的MIME类型: ``` @RequestMapping(value = "/view/{filename}", method = RequestMethod.GET) public void view(@PathVariable("filename") String filename, HttpServletResponse response) { try { // 设置响应头 response.setContentType("application/" + FilenameUtils.getExtension(filename)); // 获取文件输入流 FileInputStream fis = new FileInputStream("/path/to/file/" + filename); // 获取响应输出流 ServletOutputStream sos = response.getOutputStream(); // 将文件写入响应输出流 byte[] buffer = new byte[1024]; int len; while ((len = fis.read(buffer)) != -1) { sos.write(buffer, 0, len); } // 关闭流 sos.close(); fis.close(); } catch (IOException e) { e.printStackTrace(); } } ``` 其中,FilenameUtils.getExtension()方法用于获取文件的扩展名。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值