JAVAWeb上传文件

这篇博客介绍了前端使用form表单以multipart/form-data编码格式上传文件到后端的实现方式。后端通过MultipartFile接收文件,处理包括创建文件目录、防止重名、保存文件等操作。此外,还展示了如何下载文件,通过设置response响应头实现文件下载功能。

上传文件

首先前端用form表单上传文件

<!--enctype就是编码的意思,要想上传文件就要用multipart/form-data编码格式,往后端传二进制-->
<form action="/steal/upload" enctype="multipart/form-data" method="post">
    <input type="file" name="file"/>
    <input type="submit" value="upload"/>
</form>

后端代码

    @RequestMapping("upload")
    public ModelAndView upload(MultipartFile file,HttpServletRequest request,HttpServletResponse response) throws IOException {
        String real=request.getServletContext().getRealPath("/upload");
        String fileName=file.getOriginalFilename();
        String name=fileName.substring(0,fileName.indexOf("."));
        String suffix=fileName.substring(fileName.lastIndexOf("."));
        //创建文件目录
        //创建年月日文件夹
        Calendar date=Calendar.getInstance();
        File dateFile=new File(date.get(Calendar.YEAR)+File.separator+(date.get(Calendar.MONTH)+1));
        //目标文件
        File descFile=new File(real+File.separator+dateFile+fileName);
        //如果有重名的文件
        int i=1;
        if(descFile.exists()){
            fileName=name+"("+i+")"+suffix;
            String parentPath=descFile.getParent();
            descFile=new File(real+File.separator+dateFile+fileName);
            i++;
        }
        //判断是否有此目录
        if(!descFile.getParentFile().exists()){
            descFile.getParentFile().mkdir();
        }
        try {
            file.transferTo(descFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        ModelAndView model = new ModelAndView();
        model.setViewName("steal/views/upload");
        return model;
    }

下载文件

    public void down(HttpServletResponse response,HttpServletRequest request) throws IOException {
       //要下载的图片地址
       String path=request.getServletContext().getRealPath("/upload");
       String realName="1.jpg";
       //设置response响应头
        response.reset();
        response.setCharacterEncoding("UTF-8");
        response.setContentType("multipart/from-data");
        //设置响应头
        response.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(realName,"UTF-8"));
        File file=new File(path,realName);
        //读取文件--输入流
        InputStream input=new FileInputStream(file);
        //写出文件--输出流
        OutputStream out=response.getOutputStream();

        byte[] buff=new byte[1024];
        int index=0;
        //执行操作
        while((index=input.read(buff))!=-1){
            out.write(buff,0,index);
            out.flush();
        }
        input.close();
        out.close();
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值