文件上传与下载

文件上传:

1.导入jar包

复制代码
      <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.3</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>

        </dependency>
View Code
复制代码

2.spring配置

复制代码
<!--     文件上传  id固定-->
  <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!--      请求的编码格式.需要与JSP编码一致,默认的是ISO-8859-1-->
      <property name="defaultEncoding" value="utf-8"/>
<!--      文件上传大小限制[可省略] 单位:字节    (10M)-->
      <property name="maxUploadSize" value="10485760"/>
      <property name="maxInMemorySize" value="40960"/>
  </bean>
View Code
复制代码

3.实现

前端

复制代码
  <form action="${pageContext.request.contextPath}/upload" enctype="multipart/form-data" method="post">
    <input type="file" name="file">
    <input type="submit" value="提交">
  </form>

  <form action="${pageContext.request.contextPath}/upload2" enctype="multipart/form-data" method="post">
    <input type="file" name="file">
    <input type="submit" value="提交">
  </form>
View Code
复制代码

后端

复制代码
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;

@RestController
public class FileUpload {
    @RequestMapping("/upload")
    public String upload(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {

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

        //如果文件名为空,直接返回首页
        if ("".equals(uploadFileName)) {
            return "redirect:/index.jsp";
        }

        System.out.println("上传文件名:" + uploadFileName);

        //上传路径保存设置  UUID保证不重复名称
        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";

    }


    @RequestMapping("/upload2")
    public String upload2(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {


        //上传路径保存设置
        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 +"/"+ file.getOriginalFilename()));

        return "redirect:/index.jsp";
    }
}
View Code
复制代码

 

 

文件下载

 

 

文件下载:

方法一:

a标签href一个文件的地址,点击就可以下载

  <a href="${pageContext.request.contextPath}/download">点击下载</a>

后端代码

复制代码
    @RequestMapping(value="/download")
    public String downloads(HttpServletResponse response , HttpServletRequest request) throws Exception{
        //要下载的图片地址 upload 在橙色目录out-artifacts-下
        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 "OK";
    }
View Code
复制代码

方法二:

在web文件夹下创建一个存放静态资源的文件夹,比如statics文件夹.里面放图片 1.jpg , 直接访问就可以下载

<a href="${pageContext.request.contextPath}/statics/1.jpg">点击下载2</a>

 

相关笔记

 

 

 

 

 

 

posted @   磕伴  阅读(115)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决
· 提示词工程——AI应用必不可少的技术
点击右上角即可分享
微信分享提示