侧边栏壁纸
博主头像
coydone博主等级

记录学习,分享生活的个人站点

  • 累计撰写 306 篇文章
  • 累计创建 51 个标签
  • 累计收到 0 条评论

目 录CONTENT

文章目录

SpringMVC文件上传下载

coydone
2022-03-21 / 0 评论 / 0 点赞 / 373 阅读 / 7,291 字 / 正在检测是否收录...
温馨提示:
本文最后更新于 2022-04-10,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。

文件上传

文件上传的必要前提

1、form 表单的 enctype 取值必须是:multipart/form-data,(默认值是:application/x-www-form-urlencoded)。enctype表示表单请求正文的类型。

2、method 属性取值必须是 post。

3、提供一个文件选择域<input type="file" />

<form action="" enctype="multipart/form-data" method="post">
   <input type="file" name="file"/>
   <input type="submit">
</form>

一旦设置了enctype为multipart/form-data,浏览器即会采用二进制流的方式来处理表单数据,而对于文件上传的处理则涉及在服务器端解析原始的HTTP响应。在2003年,Apache Software Foundation发布了开源的Commons FileUpload组件,其很快成为Servlet/JSP程序员上传文件的最佳选择。

Servlet3.0规范已经提供方法来处理文件上传,但这种上传需要在Servlet中完成。而SpringMVC则提供了更简单的封装。

SpringMVC为文件上传提供了直接的支持,这种支持是用即插即用的MultipartResolver实现的。

SpringMVC使用Apache Commons FileUpload技术实现了一个MultipartResolver实现类:CommonsMultipartResolver。因此,SpringMVC的文件上传还需要依赖Apache Commons FileUpload的组件。

文件上传回顾

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页面

<h3>文件上传</h3>
<form action="user/fileupload" method="post" enctype="multipart/form-data"> 
    选择文件:<input type="file" name="upload"/><br/> 
    <input type="submit" value="上传文件"/> 
</form>

3、 编写文件上传的Controller控制器

@RequestMapping(value="/fileupload") 
public String fileupload(HttpServletRequest request) throws Exception {
    // 先获取到要上传的文件目录
    String path = request.getSession().getServletContext().getRealPath("/uploads"); 
    // 创建File对象,一会向该路径下上传文件
    File file = new File(path);
    // 判断路径是否存在,如果不存在,创建该路径
    if(!file.exists()) { 
        file.mkdirs(); 
    }
    // 创建磁盘文件项工厂
    DiskFileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload fileUpload = new ServletFileUpload(factory); 
    // 解析request对象
    List<FileItem> list = fileUpload.parseRequest(request); 
    // 遍历
    for (FileItem fileItem : list) { 
        // 判断文件项是普通字段,还是上传的文件
        if(fileItem.isFormField()) { 
        }else { 
            // 上传文件项
            // 获取到上传文件的名称
            String filename = fileItem.getName();
            // 上传文件 
            fileItem.write(new File(file, filename)); 
            // 删除临时文件 
            fileItem.delete();
        } 
    }
    return "success"; 
}

SpringMVC文件上传

1、导入文件上传的jar包,commons-fileupload , Maven会自动帮我们导入他的依赖包 commons-io包。

<!--文件上传-->
<dependency>
   <groupId>commons-fileupload</groupId>
   <artifactId>commons-fileupload</artifactId>
   <version>1.3.3</version>
</dependency>
<!--servlet-api导入高版本的-->
<dependency>
   <groupId>javax.servlet</groupId>
   <artifactId>javax.servlet-api</artifactId>
   <version>4.0.1</version>
</dependency>

2、配置bean:multipartResolver。

<!--文件上传配置-->
<bean id="multipartResolver"  class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
   <!-- 请求的编码格式,必须和jSP的pageEncoding属性一致,以便正确读取表单的内容,默认为ISO-8859-1 -->
   <property name="defaultEncoding" value="utf-8"/>
   <!-- 上传文件大小上限,单位为字节(10485760=10M) -->
   <property name="maxUploadSize" value="10485760"/>
   <property name="maxInMemorySize" value="40960"/>
</bean>

bena的id必须为:multipartResolver , 否则上传文件会报400的错误!

CommonsMultipartFile 的常用方法:

  • String getOriginalFilename():获取上传文件的原名。

  • InputStream getInputStream():获取文件流。

  • void transferTo(File dest):将上传文件保存到一个目录文件中。

3、编写控制器Controller

SpringMVC框架提供了MultipartFile对象,该对象表示上传的文件,要求变量名称必须和表单file标签的name属性名称相同。

@Controller
public class FileController {
   //@RequestParam("file") 将name=file控件得到的文件封装成CommonsMultipartFile 对象
   //批量上传CommonsMultipartFile则为数组即可
   @RequestMapping("/upload")
   public String fileUpload(@RequestParam("file") CommonsMultipartFile file , HttpServletRequest request) throws IOException {

       //获取文件名 : file.getOriginalFilename();
       String uploadFileName = file.getOriginalFilename();

       //如果文件名为空,直接回到首页!
       if ("".equals(uploadFileName)){
           return "redirect:/index.jsp";
	   }
       System.out.println("上传文件名 : "+uploadFileName);
	   
       //上传路径保存设置
       String path = request.getServletContext().getRealPath("/upload");
       //如果路径不存在,创建一个
       File realPath = new File(path);
       if (!realPath.exists()){
           realPath.mkdir();
      }
       System.out.println("上传文件保存地址:"+realPath);

       InputStream is = file.getInputStream(); //文件输入流
       OutputStream os = new FileOutputStream(new File(realPath,uploadFileName)); //文件输出流

       //读取写出
       int len=0;
       byte[] buffer = new byte[1024];
       while ((len=is.read(buffer))!=-1){
           os.write(buffer,0,len);
           os.flush();
      }
       os.close();
       is.close();
       return "redirect:/index.jsp";
  }
}

采用file.Transto 来保存上传的文件

编写Controller

/*
* 采用file.Transto 来保存上传的文件
*/
@RequestMapping("/upload2")
public String  fileUpload2(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {

    String uploadFileName = file.getOriginalFilename()
	//截取上传文件的后缀名,生成新的文件名
    String ext = uploadFileName.substring(uploadFileName.lastIndexOf(".")); //.jpg
    String fileName = System.currentTimeMillis()+ext;

   //上传路径保存设置
   String path = request.getServletContext().getRealPath("/upload");
   File realPath = new File(path);
   if (!realPath.exists()){
       realPath.mkdir();
  }
   //上传文件地址
   System.out.println("上传文件保存地址:"+realPath);

   //通过CommonsMultipartFile的方法直接写文件(注意这个时候)
   file.transferTo(new File(realPath +"/"+ fileName));
   return "redirect:/index.jsp";
}

跨服务器方式文件上传

1、导入开发需要的依赖

<dependency> 
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-core</artifactId>
    <version>1.18.1</version>
</dependency> 
<dependency> 
    <groupId>com.sun.jersey</groupId> 
    <artifactId>jersey-client</artifactId> 
    <version>1.18.1</version> 
</dependency>

2、编写文件上传的JSP页面

3、编写控制器

@RequestMapping(value="/fileupload3")
public String fileupload3(MultipartFile upload) throws Exception { 
    System.out.println("SpringMVC跨服务器方式的文件上传..."); 
    // 定义图片服务器的请求路径
    String path = "http://localhost:8080/SpringMVC_uploads/uploads/";
    // 获取到上传文件的名称 
    String filename = upload.getOriginalFilename();
    String uuid = UUID.randomUUID().toString().replaceAll("-", "").toUpperCase();
    // 把文件的名称唯一化 
    filename = uuid+"_"+filename; 
    // 向图片服务器上传文件
    // 创建客户端对象 
    Client client = Client.create(); 
    // 连接图片服务器
    WebResource webResource = client.resource(path+filename); 
    // 上传文件
    webResource.put(upload.getBytes()); 
    return "success";
}

文件下载

步骤

1、设置 response 响应头

2、读取文件——InputStream

3、写出文件——OutputStream

4、执行操作

5、关闭流 (先开后关)

代码实现

前端

<a href="/download">点击下载</a>

Controller

@RequestMapping(value="/download")
public String downloads(HttpServletResponse response ,HttpServletRequest request) throws Exception{
   //要下载的图片地址
   String  path = request.getServletContext().getRealPath("/upload");
   String  fileName = "基础语法.jpg";

   //1、设置response 响应头
   response.reset(); //设置页面不缓存,清空buffer
   response.setCharacterEncoding("UTF-8"); //字符编码
   response.setContentType("multipart/form-data"); //二进制传输数据
   //设置响应头
   response.setHeader("Content-Disposition",
           "attachment;fileName="+URLEncoder.encode(fileName, "UTF-8"));

   File file = new File(path,fileName);
   //2、 读取文件--输入流
   InputStream input=new FileInputStream(file);
   //3、 写出文件--输出流
   OutputStream out = response.getOutputStream();

   byte[] buff =new byte[1024];
   int index=0;
   //4、执行 写出操作
   while((index= input.read(buff))!= -1){
       out.write(buff, 0, index);
       out.flush();
  }
   out.close();
   input.close();
   return null;
}
0

评论区