java 文件上传下载

翻新十年前的老项目,文件上传改为调用接口方式,记录一下子~~~

  java后台代码:

//取配置文件中的上传目录
    @Value("${uploadPath}")
    String path;

    //文件上传接口
    @RequestMapping(value = "upload")
    @ResponseBody
    public String getMobileAuthCode( HttpServletRequest request,String files ,String appId,String fileUUIDs,String  myCallback)
            throws Exception {
        //文件支持多个  以逗号分隔
        String[] file=files.split(",");
        //文件生成的uuid ,以逗号分隔,防止文件重名
        String[] fileUUID=fileUUIDs.split(",");
        //本地文件
        File localFile;
        InputStream input = null;
        OutputStream output = null;
        for (int i = 0; i <file.length ; i++) {
            localFile=new File(file[i]);
            String fileName = localFile.getName();
            //获取文件类型
            String filetype=fileName.substring(fileName.indexOf("."),fileName.length());
            try {
                File var4 = new File(path+"\\" + appId);
                //若目标地址不存在,则创建
                if (!var4.exists() || var4.exists() && !var4.isDirectory()) {
                    var4.mkdirs();
                }
                //将本地文件 写入目标地址
                input = new FileInputStream(localFile);
                output = new FileOutputStream(new File(path + "\\" +appId+"\\"+ fileUUID[i]+filetype));
                byte[] buf = new byte[1024];
                int bytesRead;
                while ((bytesRead = input.read(buf)) != -1) {
                    output.write(buf, 0, bytesRead);
                }
            }catch (Exception e){
                System.out.println("文件上传失败");
                e.printStackTrace();
            }finally {
                input.close();
                output.close();
            }
        }
        String result =  "{'ret':'true'}";
        result=myCallback+"("+result+")";
        return result;
    }
    //文件下载
    @RequestMapping("downLoad")
    public ResponseEntity<byte[]> downloadFile(String fileUrl,String needFile) throws IOException {
        //获取文件路径
        HttpHeaders headers = new HttpHeaders();//http头信息
        File file = new File(path+"\\"+fileUrl);//新建一个文件
        String downloadFileName = new String(needFile.getBytes(), "iso-8859-1");
        //设置编码
        headers.setContentDispositionFormData("attachment", downloadFileName);
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
    }

   jsp 页面代码:


window.open("http://ip:port/file/downLoad?needFile="+filename+"&fileUrl="+fileurl);//下载

  

//上传

$.ajax({
    url: "http://ip:port/file/upload",
    type: 'post',
    dataType:'jsonp',
    jsonp: "callback",
    data:{
        "files":files,
        "appId":contentForm.appId.value,
        "fileUUIDs":fileUUIDs
    },
    success: function (data) {
    }
});

  

posted @ 2020-07-06 17:59  守稚心  阅读(193)  评论(0编辑  收藏  举报