锐单电子商城 , 一站式电子元器件采购平台!
  • 电话:400-990-0325

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

时间:2022-11-14 14:30:01 温度传感器wkl

文章目录

  • 1:javaWeb原生api上传下载(了解一下,平时不用)
  • 2:SpringMVC的上传下载
    • 1:上传-利用fileupload进行上传
      • 1:导包
      • 2.分析器上传配置文件
      • 三、文件上传页面
      • 四、文件上传处理器
      • 五、多文件上传
    • 2:下载-利用springmvc的ResponseEntity

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

原生javaweb文件上传下载链接

2:SpringMVC的上传下载

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

1:导包

  <dependency>   <groupId>commons-fileuploadgroupId>   <artifactId>commons-fileuploadartifactId>   <version>1.4version> 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下载文件

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

<dependency>
  <groupId>javax.servletgroupId>
  <artifactId>javax.servlet-apiartifactId>
  <version>4.0.1version>
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.mediagroupId> 
     <artifactId>jersey-media-multipartartifactId> 
     <version>2.25version>
 dependency>

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

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

	<init-param>
        <param-name>jersey.config.server.provider.classnamesparam-name>
        <param-value>org.glassfish.jersey.media.multipart.MultiPartFeatureparam-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包



<dependency>
    <groupId>org.apache.poigroupId>
    <artifactId>poiartifactId>
    <version>4.1.2version>
dependency>


<dependency>
    <groupId>javax.ws.rsgroupId>
    <artifactId>javax.ws.rs-apiartifactId>
    <version>2.1.1version>
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 

相关文章