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>

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>

注: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>

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 "文件上传成功!";
    }
}

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 "文件上传成功!";
    }

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

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

<dependency>
  <groupId>javax.servlet</groupId>
  <artifactId>javax.servlet-api</artifactId>
  <version>4.0.1</version>
</dependency>

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;


    }

}

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>

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>

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,请求必须是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";
}

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

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();

    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

苍煜

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

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

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

打赏作者

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

抵扣说明:

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

余额充值