javaweb文件上传和下载
发布日期:2021-05-14 13:23:35 浏览次数:19 分类:精选文章

本文共 8785 字,大约阅读时间需要 29 分钟。

案例1:

文件随同表单一起上传

前端页面

js代码

后台代码:

/**     * 添加歌曲     *     * @param request     * @param song     * @return     */    @PostMapping(value = "frontaddSong")    @ResponseBody    public String addSong(HttpServletRequest request, String songAuthor,                          Integer songLanguageType, MultipartFile song) {        String name = song.getOriginalFilename();        //歌曲名称需去掉.mp3的后缀        String songName = name.substring(0, name.lastIndexOf("."));        //这里上传至webapp下的track/song文件夹下        String songAddress = "track/song/" + name;        User user = (User) request.getSession().getAttribute("user");        Song song1 = new Song(songName, songAddress, songLanguageType, 1,                0, user.getUserId(), songAuthor, 0, 0);        int result = songDao.insertOnlySong(song1);        if (result > 0) {            saveFile(song, request.getServletContext().getRealPath(songAddress));            return ReturnMsg.msg(HttpServletResponse.SC_OK, "上传成功");        } else {            return ReturnMsg.msg(HttpServletResponse.SC_BAD_GATEWAY, "上传失敗");        }    }    private void saveFile(MultipartFile multipartFile, String realFilePath) {        try {            //使用输入输出缓冲流提高上传效率            InputStream fis = multipartFile.getInputStream();            BufferedInputStream bis = new BufferedInputStream(fis);            FileOutputStream fos = new FileOutputStream(realFilePath);            BufferedOutputStream bos = new BufferedOutputStream(fos);            int size = 0;            byte[] buffer = new byte[10240];            while ((size = bis.read(buffer)) != -1) {                bos.write(buffer, 0, size);            }            //刷新此缓冲的输出流,保证数据全部都能写出            bos.flush();            bis.close();            bos.close();        } catch (IOException e) {            throw new RuntimeException(e);        }    }

文件下载

//download.do?songAddress=track/song/毛不易 - 无问.mp3&songId=290	@RequestMapping(value = "download.do", method = { RequestMethod.GET})	public void download(HttpServletRequest request,HttpServletResponse response,String songAddress,int songId) throws IOException {		response.setContentType("audio/mp3");		response.setHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode(System.currentTimeMillis()+"如果不想返回名称的话.mp3", "utf8"));		BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());  		InputStream bis=null;		if(songAddress.contains("http")) {			//在另外服务器的文件			URL url = new URL(songAddress);              URLConnection uc = url.openConnection();  			bis=new BufferedInputStream(uc.getInputStream());		}else {			//在服务器内部的文件			songAddress=request.getServletContext().getRealPath(songAddress);			bis = new BufferedInputStream(new FileInputStream(new File(songAddress)));		}		int len = 0;  		while((len = bis.read()) != -1){              out.write(len);              out.flush();          }  		out.close();		bis.close();	}

案例二:

读写指定路径的文件

public static void main(String[] args){        /**         * 1.先将文件中的内容读入到缓冲输入流中         * 2.将输入流中的数据通过缓冲输出流写入到目标文件中         * 3.关闭输入流和输出流         */        try {            long begin=System.currentTimeMillis();            FileInputStream fis=new FileInputStream("BISDemo.txt");            BufferedInputStream bis=new BufferedInputStream(fis);            FileOutputStream fos=new FileOutputStream("BOSDemo.txt");            BufferedOutputStream bos=new BufferedOutputStream(fos);            int size=0;            byte[] buffer=new byte[10240];            while((size=bis.read(buffer))!=-1){                bos.write(buffer, 0, size);            }            //刷新此缓冲的输出流,保证数据全部都能写出            bos.flush();            bis.close();            bos.close();            long end=System.currentTimeMillis();            System.out.println("使用缓冲输出流和缓冲输入流实现文件的复制完毕!耗时:"+(end-begin)+"毫秒");        } catch (Exception e) {                e.printStackTrace();        }    }

案例三:springmvc中后台如何接受上传文件方法

private void saveFile(MultipartFile multipartFile, String realFilePath) {        try {            InputStream fis = multipartFile.getInputStream();            BufferedInputStream bis = new BufferedInputStream(fis);            FileOutputStream fos = new FileOutputStream(realFilePath);            BufferedOutputStream bos = new BufferedOutputStream(fos);            int size = 0;            byte[] buffer = new byte[10240];            while ((size = bis.read(buffer)) != -1) {                bos.write(buffer, 0, size);            }            //刷新此缓冲的输出流,保证数据全部都能写出            bos.flush();            bis.close();            bos.close();        } catch (IOException e) {            throw new RuntimeException(e);        }    }

案例四:异步上传文件

表单html

农作物编辑

农作物名称

特性

生长环境

产地

图片

${crop.info}

操作

js代码

后端代码

@ResponseBody    @PostMapping("/addcrop")    public Result addcrop(Integer id, HttpServletRequest request, String title, String info,                          Integer typeid, String feature, String location,                          String environment, @RequestParam("img") MultipartFile img) throws IOException {        if (id != null) {            //修改            String fileName = null;            if (!img.isEmpty()) {                //根据时间戳创建新的文件名,这样即便是第二次上传相同名称的文件,也不会把第一次的文件覆盖了                fileName = System.currentTimeMillis() + img.getOriginalFilename();                //通过req.getServletContext().getRealPath("") 获取当前项目的真实路径,然后拼接前面的文件名,这个是web项目情况 如果是jar项目,不能使用这个                String destFileName = request.getServletContext().getRealPath("") + "upload" + File.separator + fileName;                File destFile = new File(destFileName);                //把浏览器上传的文件复制到希望的位置                img.transferTo(destFile);                //6.把文件名放在model里,以便后续显示用            }            Crop crop=null;            if(img.getOriginalFilename().equals("")){                 crop = new Crop(id, title, null, info, new Date(),                        typeid, feature, location, environment);            }else{                 crop = new Crop(id, title, "/upload/" + fileName, info, new Date(),                        typeid, feature, location, environment);            }            cropMapper.updateByPrimaryKey(crop);            return new Result(200);        } else {//添加            String fileName = null;            if (!img.isEmpty()) {                //根据时间戳创建新的文件名,这样即便是第二次上传相同名称的文件,也不会把第一次的文件覆盖了                fileName = System.currentTimeMillis() + img.getOriginalFilename();                //通过req.getServletContext().getRealPath("") 获取当前项目的真实路径,然后拼接前面的文件名                String destFileName = request.getServletContext().getRealPath("") + "upload" + File.separator + fileName;                File destFile = new File(destFileName);                //把浏览器上传的文件复制到希望的位置                img.transferTo(destFile);            }            Crop crop = new Crop(id, title, "/upload/" + fileName, info, new Date(),                    typeid, feature, location, environment);            cropMapper.insert(crop);            return new Result(200);        }    }

 

 

上一篇:window安装mysql详细过程
下一篇:Springboot如何发送邮件

发表评论

最新留言

能坚持,总会有不一样的收获!
[***.219.124.196]2025年04月13日 09时37分31秒