java 文件上传和下载

java最基本的文件上传和下载

上传后对上传的文件进行重新命名处理,不然上传了重复的文件会覆盖之前的文件:

    /**
     * 上传图片
     * @param file
     * @return
     * @throws Exception
     */
    @RequestMapping("/uploadFile")
    @ResponseBody
     public JsonResult uploadFile(@RequestParam(value = "file") MultipartFile file)throws Exception{


        String sufferName = file.getOriginalFilename();
        if (file!=null) {

            //获取文件的后缀名
            String subffix = sufferName.substring(sufferName.lastIndexOf(".") + 1, sufferName.length());

            String path = PropertiesValue.getString("path");//文件暂时存放
            File targetFile = new File(path);
            if(!targetFile.isDirectory()) targetFile.mkdirs();
            //对文件名进行处理
            String fileName = DateUtil.formatDate(DateUtil.getTime(), "yyyyMMddHHmmss")+DateUtil.randomChar(3)+ "." + subffix;
            file.transferTo(new File(path + fileName));
        }
        return JsonResult.success();

    }

文件的下载,需对文件的后缀进行基本的定义:下载即为文件复制的过程

    /**
     * 下载文件
     * @param name
     * @param resp
     * @throws Exception
     */
    @RequestMapping(value = "/downFile",method = RequestMethod.GET)
    public void downFile(String name, HttpServletResponse resp)throws Exception{

        resp.setContentType("application/force-download");//设置响应类型

        String path = "F:\\"+name;
        InputStream in = new FileInputStream(path);
        name = URLEncoder.encode(name,"UTF-8");
        resp.setHeader("Content-disposition", "attachment;  filename=\"" + name + "\"");
        resp.setContentLength(in.available());
        //开始copy
        OutputStream out = resp.getOutputStream();
        byte[] b = new byte[1024];
        int len = 0 ;
        while((len = in.read(b))!=-1){
            out.write(b,0,len);
        }
        out.flush();
        out.close();
        in.close();
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值