• JavaWeb-23-java所有框架的文件上传下载


    1:javaWeb原生api上传下载(了解一下就行,平时不用)

    原生javaweb文件上传下载链接

    2:SpringMVC的上传下载

    1:上传-利用fileupload进行上传

    1:导包

    <!--文件上传的jar包-->
    <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.4</version>
    </dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    2:配置文件上传解析器

    <!--配置文件解析器-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="#{10240000}"></property>
        <property name="defaultEncoding" value="utf-8"></property>
    </bean>
    
    • 1
    • 2
    • 3
    • 4
    • 5

    注:multipartResolver,如下图源码,这是默认的;
    在这里插入图片描述

    3:文件上传页面

    <form action="/upload" method="post" enctype="multipart/form-data">
        用户文件:<input type="file" name="filename"><br/>
        用户名:  <input type="text" name="username"><br/>
        <input type="submit" value="提交">
     
    </form>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    4:文件上传处理器

    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.bind.annotation.ResponseBody;
    import org.springframework.web.multipart.MultipartFile;
    import springfox.documentation.schema.Model;
    
    import java.io.File;
    import java.io.IOException;
    
    @Controller
    public class FileUploadController {
    
        @ResponseBody
        @RequestMapping(value = "/upload",method = RequestMethod.POST)
        public String upload(@RequestParam(value = "username",required = false)String username,
                             @RequestParam("filename") MultipartFile multipartFile, Model model){
            System.out.println("username:"+username);
            //这是页面上的文件字段的字段名
            System.out.println("finename:"+multipartFile.getName());
            //文件的名字
            System.out.println("finename:"+multipartFile.getOriginalFilename());
    
            try {
                //保存文件
                multipartFile.transferTo(new File("F:\\"+multipartFile.getOriginalFilename()));
                System.out.println("end");
            } catch (IOException e) {
                e.printStackTrace();
            }
    
            return "文件上传成功!";
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35

    5:多文件上传

    @ResponseBody
        @RequestMapping(value = "/uploads",method = RequestMethod.POST)
        public String uploads(@RequestParam(value = "username",required = false)String username,
                             @RequestParam("filename")MultipartFile[] multipartFiles, Model model){
            System.out.println("username:"+username);
     
            try {
                for(MultipartFile file:multipartFiles){
                    //保存文件
                    file.transferTo(new File("F:\\haha\\"+file.getOriginalFilename()));
     
                }
                System.out.println("end");
            } catch (IOException e) {
                e.printStackTrace();
            }
     
            return "文件上传成功!";
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    2:下载-利用springmvc的ResponseEntity<byte[]>下载文件

    1:导入原生api包,方便使用原生HttpServletRequest

    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>4.0.1</version>
    </dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5

    2:利用文件流获取文件并封装到ResponseEntity

    package com.wkl;
    
    import org.springframework.http.HttpHeaders;
    import org.springframework.http.HttpStatus;
    import org.springframework.http.ResponseEntity;
    import org.springframework.stereotype.Controller;
    import org.springframework.util.MultiValueMap;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    
    import javax.servlet.ServletContext;
    import javax.servlet.http.HttpServletRequest;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.io.InputStream;
    
    /**
     * @author wkl
     * @create 2022-06-24 19:02
     */
    @Controller
    @RequestMapping("/test")
    public class testController {
        @RequestMapping(value = "/exportFile", method = RequestMethod.GET)
        public ResponseEntity<byte[]> exportActivityForSearch(HttpServletRequest httpRequest) {
            //得到请求路径
            String contextPath = httpRequest.getContextPath();
            //找到系统的根路径
            ServletContext servletContext = httpRequest.getServletContext();
            //得到文件的真实路径-也可以从系统中获取
            String realPath = servletContext.getRealPath("/WEB-INF/dispatcher-servlet.xml");
            System.out.println("上边可以从系统中获取绝对路径:"+realPath);
    
            //拿到文件流
            InputStream fileInputStream = null;
            ResponseEntity<byte[]> stringResponseEntity = null;
            try {
                fileInputStream = new FileInputStream("E:\\DevelopAPI\\Jquery\\jquery1.7_20120209.xlsx");
                byte[] tmp = new byte[fileInputStream.available()];
    
                fileInputStream.read(tmp);
                //设置请求头,制定文件类型和文件名称
                String fileName = "导出_"+System.currentTimeMillis();
                MultiValueMap headers = new HttpHeaders();
                headers.add("Content-disposition", "attachment;filename=" + new String(fileName.getBytes("utf-8"), "ISO8859-1") + ".xlsx");
    
                stringResponseEntity = new ResponseEntity<byte[]>(tmp, headers, HttpStatus.OK);
            } catch (FileNotFoundException e) {
                //打印异常日志
            } catch (IOException e) {
                //打印异常日志
            }finally {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    //打印异常日志
                }
    
            }
            return stringResponseEntity;
    
    
        }
    
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67

    3:jersey框架上传下载

    jersey框架是什么,请看这篇文章:Jersey框架和springmvc框架

    1:jersey框架上传

    1:导包-maven中添加multipart的依赖:

    <dependency> 
         <groupId>org.glassfish.jersey.media</groupId> 
         <artifactId>jersey-media-multipart</artifactId> 
         <version>2.25</version>
     </dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5

    2:配置-需要在Jersey中引入MultipartFeature。MultiPartFeature是Jersey中针对Multipart的一种特征。

    在web.xml中注册:只需要在Jersey的ServletContainer中添加initparam即可:

    	<init-param>
            <param-name>jersey.config.server.provider.classnames</param-name>
            <param-value>org.glassfish.jersey.media.multipart.MultiPartFeature</param-value>
        </init-param>
    
    
    • 1
    • 2
    • 3
    • 4
    • 5

    3:第一种方式我们采用的是直接使用InputStream来提供上传文件的输入流;

    @POST
    @Path("image1")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    public String upload(@FormDataParam("file") InputStream fileInputStream,
            @FormDataParam("file") FormDataContentDisposition disposition, @Context ServletContext ctx) {
     
        File upload = new File(ctx.getRealPath("/upload"),
                UUID.randomUUID().toString() + "." + FilenameUtils.getExtension(disposition.getFileName()));
        try {
            FileUtils.copyInputStreamToFile(fileInputStream, upload);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "success";
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    简单解释一下这段代码:
    1,请求必须是POST的,这个不用多说;
    2,请求返回json格式响应;
    3,Consumes这次设置的是MediaType.MULTIPART_FORM_DATA,这个很重要,因为要能够上传,需要要求表单的提交格式为multipart/form-data;
    4,重点在于资源方法的参数,在这里,我们使用了@FormDataParam(该标签来源于jersey的multipart包),该标签能够在资源方法上绑定请求编码类型为multipart/form-data中的每一个实体项

    4:第二种方式,我们使用较为底层的FormDataBodyPart来完成。综合两种方式,更建议使用第一种方式来完成文件上传

    @POST
    @Path("image2")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    public String upload2(@FormDataParam("file") FormDataBodyPart bp, @Context ServletContext ctx) {
        File upload = new File(ctx.getRealPath("/upload"), UUID.randomUUID().toString() + "."
                + FilenameUtils.getExtension(bp.getFormDataContentDisposition().getFileName()));
        try {
            FileUtils.copyInputStreamToFile(bp.getValueAs(InputStream.class), upload);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "success";
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    2:jersey框架下载

    1:导包-导入原生的javax包

    <!--aapache的导入导出文件工具类-->
    <!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi</artifactId>
        <version>4.1.2</version>
    </dependency>
    <!--返回响应的Respose-->
    <!-- https://mvnrepository.com/artifact/javax.ws.rs/javax.ws.rs-api -->
    <dependency>
        <groupId>javax.ws.rs</groupId>
        <artifactId>javax.ws.rs-api</artifactId>
        <version>2.1.1</version>
    </dependency>
    ————————————————
    版权声明:本文为CSDN博主「苍煜」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
    原文链接:https://blog.csdn.net/qq_41694906/article/details/107200144
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    2:利用Respose来返回文件流

    package com.wkl;
    
    import com.alibaba.fastjson.JSONObject;
    import com.engine.core.impl.Service;
    import javax.ws.rs.core.Response;
    import java.io.ByteArrayOutputStream;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.net.URLEncoder;
    import java.util.Map;
    
    /**
     * @author wkl
     * @create 2022-06-24 19:36
     */
    @Path("/downloaddetail")
    public class DownloadController {
        @GET
        @Path("/downloadDetail")
        @Produces(MediaType.APPLICATION_OCTET_STREAM)
        public Response downloadDetail(@Context HttpServletRequest request){
            InputStream in = null;
            ByteArrayOutputStream bos = null;
            try {
                String fileName = "";
                String contentType = "";
                String substring = fileName.substring(fileName.lastIndexOf("."));
                JSONObject contype = this.getContype();
    
                in = new FileInputStream("E:\\DevelopAPI\\Jquery\\jquery1.7_20120209.xlsx");
    
    
                bos = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int len = 0;
    
                while((len = in.read(buffer)) != -1) {
                    bos.write(buffer, 0, len);
                }
    
                return Response.ok(bos.toByteArray())
                        .header("Content-disposition", "attachment;filename=" +  URLEncoder.encode(fileName, "UTF-8"))
                        .header("Cache-Control", "no-cache")
                        .header("content-type", contentType ).build();
    
            }catch (Exception e){
                bs.writeLog(this.getClass().getName()+"------DoccumentImpl : downUpload  Exception---"+e.getMessage(),e);
    
            }finally {
                try {
                    if(in != null) {
                        in.close();
                    }
                    if(bos != null) {
                        bos.close();
                    }
                }catch (IOException e){
                    bs.writeLog(this.getClass().getName()+"------DoccumentImpl : downUpload  Exception---"+e.getMessage(),e);
                }
            }
            return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
    
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
  • 相关阅读:
    【实战】Mysql 千万级数据表结构变更 、含脚本
    Nginx网站服务(安装nginx,nginx访问配置)
    拓展上机课题解22/10/21
    HttpClient学习(Java)
    服务器推送数据之websocket、socket.io及实现简易聊天系统
    工具篇 | WSL使用入门教程以及基于WSL和natApp内网穿透实践 - 对比VMWare
    R语言survminer包的ggsurvplot函数可视化生存曲线、legend.title指定图例的标题、legend.labs指定图例标签文本
    链接概念介绍
    如何判断一个英文单词中是否存在重复字母
    爬虫之re数据清洗
  • 原文地址:https://blog.csdn.net/qq_41694906/article/details/125450853