html下载文件和上传文件(图片)(java后台(HttpServlet))打开保存路径和选择文件录取+(乱码UTF-8)+包
下载文件:
//通过路径得到一个输入流 String path = "获取需要下载的文件路径"; //path.lastIndexOf(".")+1可以获取文件后缀名字 如:doc等 //this.getServletContext().getRealPath("");可以访问当前服务器地址 String fileName="保存文件的名称" ; //设置保存文件的乱码问题 String encodedfileName = null; String agent = request.getHeader("USER-AGENT"); if(null != agent && -1 != agent.indexOf("MSIE")){//IE encodedfileName = java.net.URLEncoder.encode(fileName,"UTF-8"); }else if(null != agent && -1 != agent.indexOf("Mozilla")){ encodedfileName = new String (fileName.getBytes("UTF-8"),"iso-8859-1"); }else{ encodedfileName = java.net.URLEncoder.encode(fileName,"UTF-8"); } //设置响应格式 response.setHeader("content-disposition", "attachment;filename=encodedfileName); //输入流,获得文件的字节流 InputStream is=new FileInputStream(path);//path是下载文件的路径 byte[] bytes=new byte[is.available()]; is.read(bytes); //将字节流写入response中 response.getOutputStream().write(bytes); is.close(); response.flushBuffer(); response.getOutputStream().flush();
上传文件:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | //设置上传的路径 String savePath= this .getServletConfig().getServletContext().getRealPath( "" ); File file= new File(savePath); //判断是否存在 不存在就创建 if (!file.exists()){ file.mkdirs(); } DiskFileItemFactory fac= new DiskFileItemFactory(); ServletFileUpload upload= new ServletFileUpload(fac); upload.setHeaderEncoding( "utf-8" ); List<FileItem> filelist= null ; try { filelist=upload.parseRequest(request); } catch (FileUploadException e) { // TODO Auto-generated catch block return ; } Iterator<FileItem> it=filelist.iterator(); String name= "" ; String extName= "" ; while (it.hasNext()){ FileItem item=it.next(); if (!item.isFormField()){ name=item.getName(); long size=item.getSize(); String type=item.getContentType(); //判断是否为空 if (name== null ||name.trim().equals( "" )){ continue ; } if (name.lastIndexOf( "." )>= 0 ){ extName=name.substring(name.lastIndexOf( "." )); } File files= null ; name=id; files= new File(savePath+name+extName); try { item.write(files); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }<br> response.getWriter().print( "上传成功" ); } |
需要两个包:
commons-io-1.4.jar
commons-fileupload-1.2.1.jar
下载地址:https://github.com/weibanggang/iofilego
希望能够帮助大家,有问题请留言,感谢!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· 一文读懂知识蒸馏
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下