
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
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); } }
发表评论
最新留言
能坚持,总会有不一样的收获!
[***.219.124.196]2025年04月13日 09时37分31秒
关于作者

喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
Utils-verifyType 验证数据类型,是否允许转型
2021-05-16
Thymeleaf 生成下标,索引,使用Stat变量
2021-05-16
全局变量初始化顺序的不确定性引发的bug
2021-05-16
用std容器做接口参数应注意的问题
2021-05-16
【C++11】std::function和std::bind
2021-05-16
java基础避坑(二)——基础数据类型short
2021-05-16
Hyper ledger Caliper官方文档【中文版】
2021-05-16
ERC1155多合一代币开发教程【Solidity合约】
2021-05-16
超过250个以太坊开发工具【2021最新】
2021-05-16
以太坊NFT通证制作工具【EIP-721/1155】
2021-05-16
EOS交易离线签名PHP代码
2021-05-16
RTX2080 Super与RTX2080 的区别
2021-05-16
rx580和gtx1060区别大不大选哪个
2021-05-16
i7 9750h和r5 3550h 哪个好
2021-05-16
机械革命z3pro和x8pro 有什么区别 哪个好详细配置对比
2021-05-16
机械革命Z3 Pro和机械革命蛟龙7有什么区别 哪个好详细配置对比
2021-05-16
i9 11900H和i7 10875h 选哪个
2021-05-16
autojs-读写ini
2021-05-16
case when then else end 及cheak约束
2021-05-16