vue+java上传下载(包括解析zip包)

上传到项目下,路径写法:

// 获取根目录
File temp = null;
temp = new File(ResourceUtils.getURL("classpath:").getPath());
String path = temp.getAbsolutePath();
// 如果是在eclipse中运行,则和target同级目录,如果是jar部署到服务器,则默认和jar包同级
path = path.replace("\\target\\classes", "\\src\\main\\resources\\static\\upload");



      
        

上传

信息

选取文件
只能上传jpg/png文件,且不超过500kb
//变量 importDialogVisible:false, fileList: [], upload_method:this.HOST + '/upload1' //方法 submitUpload() { this.$refs.upload.submit(); }, handleRemove(file, fileList) { console.log(file, fileList); }, handlePreview(file) { console.log(file); }, importInfo(row){ this.importDialogVisible = true; console.log(row) }

第一种:上传普通文件(如图片,表格等)

@RequestMapping("/upload1")
@ResponseBody
public void Upload1(@RequestParam MultipartFile file, HttpServletRequest request)throws IOException {
        InputStream in = file.getInputStream();
        String packageName = file.getOriginalFilename();
        File tempFile = saveTempFile(in, packageName,request);//将上传的文件保存到本地
        
        //上传文件后,接下来把文件名,路径存到数据库中,tempFile为文件路径
        //.......
        //.......
}


public File saveTempFile(InputStream is, String fileName,HttpServletRequest request){
        File temp = null;
        //String path = request.getServletContext().getRealPath("/uploads");
        String path = "D:\\uploads";

        if(path!=null && is!=null){
            temp = new File(String.format("%s\\%s",path,fileName));
            if(!temp.exists()){
                temp.getParentFile().mkdir();//不存在则创建目录
                BufferedInputStream bis = null;
                BufferedOutputStream bos = null;
                try{
                    bis = new BufferedInputStream(is);
                    bos = new BufferedOutputStream(new FileOutputStream(temp));                                                        
                    //把文件流转为文件,保存在临时目录
                    int len = 0;
                    byte[] buf = new byte[10*BYTESIZE];                                                    
                    //缓冲区
                    while((len=bis.read(buf)) != -1){
                        bos.write(buf, 0, len);
                    }
                    bos.flush();
                }catch(IOException e){
                    e.printStackTrace();
                }finally{
                    try {
                        if(bos!=null) bos.close();
                        if(bis!=null) bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

        }
        return temp;
    }

第二种:解压zip文件后再上传里面的文件,如zip等

@RequestMapping("/Upload2")
@ResponseBody
public void Upload2(@RequestParam MultipartFile file, HttpServletRequest request) throws IOException {
        InputStream in = file.getInputStream();
        String packageName = file.getOriginalFilename();
        Charset gbk = Charset.forName("gbk");
        ZipInputStream zin = new ZipInputStream(in,gbk);
        ZipEntry ze;
        byte[] bytes = null;
        BufferedInputStream bs = new BufferedInputStream(zin);
        while((ze = zin.getNextEntry()) != null){
            if(ze.toString().endsWith("")){
                String fileName = ze.getName();//文件名
                bytes = new byte[(int) ze.getSize()];
                bs.read(bytes, 0, (int) ze.getSize());
                InputStream byteArrayInputStream = new ByteArrayInputStream(bytes);//输入流
                File tempFile = saveTempFile(byteArrayInputStream, fileName,request);
                
                //上传文件后,接下来把文件名,路径存到数据库中,tempFile为文件路径
                //.......
                //.......


                //获取zip里文件的具体内容
                //if(ze.toString().endsWith("txt")){
                //BufferedReader br = new BufferedReader(
                //new InputStreamReader(zf.getInputStream(ze)));
                //String line;
                //while((line = br.readLine()) != null){
                //System.out.println(line.toString());
                //}
                //br.close();
                //}
                //System.out.println();



            }
        }
        zin.closeEntry();
}




     /**
     * 将文件流保存在项目WEB-INF/temp目录下,并且返回这个文件;
     * @param is              待转化的文件流
     * @param fileName        临时文件名
     * @return
     * @throws IOException
     */
    public File saveTempFile(InputStream is, String fileName,HttpServletRequest request){
        File temp = null;
        //String path = request.getServletContext().getRealPath("./uploads");
        String path = "D:\\uploads";

        if(path!=null && is!=null){
            temp = new File(String.format("%s\\%s",path,fileName));
            if(!temp.exists()){
                temp.getParentFile().mkdir();
                BufferedInputStream bis = null;
                BufferedOutputStream bos = null;
                try{
                    bis = new BufferedInputStream(is);
                    bos = new BufferedOutputStream(new FileOutputStream(temp));                                        
                    //把文件流转为文件,保存在临时目录
                    int len = 0;
                    byte[] buf = new byte[10*BYTESIZE];                                                    
                    //缓冲区
                    while((len=bis.read(buf)) != -1){
                        bos.write(buf, 0, len);
                    }
                    bos.flush();
                }catch(IOException e){
                    e.printStackTrace();
                }finally{
                    try {
                        if(bos!=null) bos.close();
                        if(bis!=null) bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

        }
        return temp;
    }

配置需要设置,限定上传大小:

spring:
  servlet:
    multipart:
      max-file-size: 100MB
      max-request-size: 100MB

vue+java上传下载(包括解析zip包)_第1张图片

vue+java上传下载(包括解析zip包)_第2张图片

参考资料:springmvc上传zip文件解析,并获取每个zipEntry的输入流

java zip解析

下载文件:

download(){
        this.$axios({
          method: 'get',
          url: this.HOST + "/download",
          params: {},
          responseType: "blob"
        }).then((result) => {
          let data = result.data;
          let url = window.URL.createObjectURL(new Blob([data]));
          let link = document.createElement("a");// 创建a标签并点击, 即触发下载
          link.style.display = "none";
          link.href = url;
          link.setAttribute("download", "123.txt");
          document.body.appendChild(link);
          link.click();
          console.log('download---',result);
        });
}

后端:

方法一:

/**
* @param resp
* @param name         文件真实名字
* @param downloadName 文件下载时名字
*/
public static void download(HttpServletResponse resp, String name, String downloadName) {
        //name         文件真实名字
        //downloadName 文件下载时名字
        String fileName = null;
        try {
            fileName = new String(downloadName.getBytes("GBK"), "ISO-8859-1");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //  /home/tomcat/apache-tomcat-9.0.1/files
        String realPath = "D:" + File.separator + "apache-tomcat-8.5.15" + File.separator 
        + "files";
//String realPath=File.separator+"home"+File.separator+"tomcat"+File.separator+"apache-tomcat-9.0.1"+File.separator+"files";
        String path = realPath + File.separator + name;//文件路径 如D:\\123.txt
        File file = new File(path);
        resp.reset();
        resp.setContentType("application/octet-stream");
        resp.setCharacterEncoding("utf-8");
        resp.setContentLength((int) file.length());
        resp.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        byte[] buff = new byte[1024];
        BufferedInputStream bis = null;
        OutputStream os = null;
        try {
            os = resp.getOutputStream();
            bis = new BufferedInputStream(new FileInputStream(file));
            int i = 0;
            while ((i = bis.read(buff)) != -1) {
                os.write(buff, 0, i);
                os.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                bis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

方法二:

    @RequestMapping("/download")
    @ResponseBody
    public void download(HttpServletResponse response) throws IOException {
        //文件所在目录路径
        String filePath = "D://server.xlsx";//此路径应该从前台传入

        System.out.println("文件路径:" + filePath);

        //得到该文件
        File file = new File(filePath);
        if(!file.exists()){
            System.out.println("Have no such file!");
            return ;//文件不存在就退出方法
        }

        FileInputStream fileInputStream = new FileInputStream(file);
        //设置Http响应头告诉浏览器下载这个附件,下载的文件名也是在这里设置的
        response.setHeader("Content-Disposition", "attachment;Filename=" +         
   URLEncoder.encode("server.xlsx", "UTF-8"));
        OutputStream outputStream = response.getOutputStream();
        byte[] bytes = new byte[2048];
        int len = 0;
        while ((len = fileInputStream.read(bytes))>0){
            outputStream.write(bytes,0,len);
        }
        fileInputStream.close();
        outputStream.close();
    }

你可能感兴趣的:(java)