web开发中常用的上传下载代码

简介:

1、常用上传代码

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
/**
      * 
      * @param upload  上传文件
      * @param reaName 名称
      * @param uploadType 类型
      * @return
      * @throws IOException
      */
     public  String uploadFile(File upload, String reaName,
             String uploadType)  throws  IOException {
         String uploadpath= "D:/csg" ;
         String uploadpath2= "/upload/image/" ;
         String fileDir = uploadpath +uploadpath2;
         OutputStream os =  null ;
         InputStream is =  null ;
         File file= new  File(fileDir);
         if (!file.exists()){
             file.mkdirs();
         }
         try  {
             is =  new  FileInputStream(upload); 
             os =  new  FileOutputStream(fileDir + reaName);
             int  bytesRead =  0 ;
             byte [] buffer =  new  byte [ 8192 ];
             while  ((bytesRead = is.read(buffer,  0 ,  8192 )) != - 1 )
                 os.write(buffer,  0 , bytesRead);
         }  catch  (IOException e) {
             e.printStackTrace();
         }  finally  {
             if  (os !=  null ) {
                 os.close();
             }
             if  (is !=  null ) {
                 is.close();
             }
         }
         return  uploadpath2+reaName;
     }

此方法基本上可以上传所有附件

2、上传缩略图代码(按一定比例缩放)

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
public  String uploadFile(File upload, String reaName,
             String uploadType)  throws  IOException {
         String uploadpath= "D:/csg" ;
         String uploadpath2= "/upload/image/small/" ;
         String fileDir = uploadpath +uploadpath2;
         InputStream is =  null ;
         BufferedImage bis =  null ;
         is =  new  FileInputStream(upload); 
         File file= new  File(fileDir);
         if (!file.exists()){
             file.mkdirs();
         }
         try  {
             File reviaryFile =  new  File(fileDir +  "small20130606.jpg" );
             AffineTransform transform =  new  AffineTransform();
             bis = ImageIO.read(is);
             int  w = bis.getWidth();
             int  h = bis.getHeight();
             int  newWidth = ( int ) (w *  0 .1D);
             int  newHight = ( int ) (h *  0 .1D);
             transform.setToScale( 0.1 ,  0.1 );
             AffineTransformOp ato =  new  AffineTransformOp(transform,  null );
             BufferedImage bid =  new  BufferedImage(newWidth, newHight,  5 );
             ato.filter(bis, bid);
             ImageIO.write(bid,  "jpg" , reviaryFile);
         }  catch  (Exception e) {
             System.out.println( "上传缩略图失败" );
         } finally {
             if  (is !=  null ) {
                 is.close();
             }
         }
         return  fileDir;
     }

3、上传缩略图代码(指定比例缩放)

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
public  String uploadFile(File upload, String reaName,
             String uploadType)  throws  IOException {
         String uploadpath= "D:/csg" ;
         String uploadpath2= "/upload/image/small/" ;
         String fileDir = uploadpath +uploadpath2;
         InputStream is =  null ;
         BufferedImage bis =  null ;
          Image srcUpload =  null ;
         is =  new  FileInputStream(upload); 
         File file= new  File(fileDir);
         if (!file.exists()){
             file.mkdirs();
         }
         try  {
              srcUpload = ImageIO.read(is);
              int  newWidth =  0 , newHight =  0 ;
              int  w = srcUpload.getWidth( null );
              int  h = srcUpload.getHeight( null );
              if  (w >= h) {
                  newWidth =  90 ;
                  newHight = h *  90  / w;
              }  else  {
                  newHight =  90 ;
                  newWidth = w *  90  / h;
              }
              BufferedImage image =  new  BufferedImage(newWidth, newHight,
                      BufferedImage.TYPE_3BYTE_BGR);
              image.getGraphics().drawImage(srcUpload.getScaledInstance(newWidth, newHight, Image.SCALE_SMOOTH),  0 ,  0 ,  null );
              FileOutputStream out =  new  FileOutputStream(fileDir +  "/"  +  "small123.jpg" );
              JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
              encoder.encode(image);
              image.flush();
              out.flush();
              out.close();
              System.gc();
         }  catch  (Exception e) {
             System.out.println( "上传缩略图失败" );
         } finally {
             if  (is !=  null ) {
                 is.close();
             }
         }
         return  fileDir;
     }


4、常用下载代码(根据路劲下载)

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
Dao dao =  new  Dao();
         UploadFiles files = dao.querykById(id);
         String uploadpath =  "D:/csg" ;
         String path = uploadpath + files.getPath();
         InputStream bis =  null ;
         OutputStream bos =  null ;
         try  {
             File fileInstance =  new  File(path);
             if  (!fileInstance.exists()) {
                 System.out.println( "---------下载文件不存在,请联系管理员-------------" );
             }  else  {
                 HttpServletResponse response = (HttpServletResponse) ActionContext
                         .getContext().get(ServletActionContext.HTTP_RESPONSE);
                 bis =  new  BufferedInputStream( new  FileInputStream(fileInstance));
                 bos =  new  BufferedOutputStream(response.getOutputStream());
 
                 response.setContentType( "application/octet-stream;charset=UTF-8" );
                 response.setHeader( "Content-Disposition" , "attachment;filename=" + URLEncoder.encode(files.getUploadRealName(), "UTF-8" ));
                 byte [] buff =  new  byte [ 1024 ];
                 int  bytesRead;
                 while  (- 1  != (bytesRead = bis.read(buff,  0 , buff.length))) {
                     // 将buff中的数据写到客户端的内存
                     bos.write(buff,  0 , bytesRead);
                 }
                 bos.close();
                 bis.close();
             }
         }  catch  (IOException e) {
             System.out.println( "下载失败" );
         }  finally  {
             bos.close();
             bis.close();
         }
         return  null ;
     }


此方法基本可以下载所有附件

5、直接下载(无路径,后台生成之后直接下载适合Excel,word,pdf等)

Excel:

1
2
3
4
5
6
7
8
public  static  void  export(HttpServletResponse response,Workbook wb,String fileName) throws  Exception{
         response.setHeader( "Content-Disposition" ,  "attachment;filename=" + new  String(fileName.getBytes( "utf-8" ), "iso8859-1" ));
         response.setContentType( "application/ynd.ms-excel;charset=UTF-8" );
         OutputStream out=response.getOutputStream();
         wb.write(out);
         out.flush();
         out.close();
     }

PDF:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
ByteArrayOutputStream ba =  new  ByteArrayOutputStream();
PdfWriter writer = PdfWriter.getInstance(document, ba);
// 打开文档,生成页头页脚等信息在open之前
document.open();
//省略n行生成table的代码
document.add(table);
document.close();
// 关闭文本,释放资源
HttpServletResponse response= super .getResponse();
response.setContentLength(ba.size());
response.setContentType( "application/octet-stream;charset=UTF-8" );
String str= "审核表.pdf" ;
response.setHeader( "Content-Disposition" ,  "attachment;filename=" + new  String(str.getBytes( "utf-8" ), "iso8859-1" ));
ServletOutputStream out = response.getOutputStream();
ba.writeTo(out);
out.flush();

ps:直接下载就是在生成之后直接将文本信息传进来,就行了。而Excel这个例子是需要将生成之后的Workbook返回去,传给export方法!PDF,Excel,word直接下载方法基本类似!


上传下载说白了,其实就是输入,输出流的问题!了解输入输出流的本质这些基本上就不是问题了!


以上代码都是经本人测试之后拷贝出来直接可以使用!










本文转自 小夜的传说 51CTO博客,原文链接:http://blog.51cto.com/1936625305/1423041,如需转载请自行联系原作者
目录
相关文章
|
算法 Java Go
【GoGin】(1)上手Go Gin 基于Go语言开发的Web框架,本文介绍了各种路由的配置信息;包含各场景下请求参数的基本传入接收
gin 框架中采用的路优酷是基于httprouter做的是一个高性能的 HTTP 请求路由器,适用于 Go 语言。它的设计目标是提供高效的路由匹配和低内存占用,特别适合需要高性能和简单路由的应用场景。
831 4
|
缓存 JavaScript 前端开发
鸿蒙5开发宝藏案例分享---Web开发优化案例分享
本文深入解读鸿蒙官方文档中的 `ArkWeb` 性能优化技巧,从预启动进程到预渲染,涵盖预下载、预连接、预取POST等八大优化策略。通过代码示例详解如何提升Web页面加载速度,助你打造流畅的HarmonyOS应用体验。内容实用,按需选用,让H5页面快到飞起!
|
JavaScript 前端开发 API
鸿蒙5开发宝藏案例分享---Web加载时延优化解析
本文深入解析了鸿蒙开发中Web加载完成时延的优化技巧,结合官方案例与实际代码,助你提升性能。核心内容包括:使用DevEco Profiler和DevTools定位瓶颈、四大优化方向(资源合并、接口预取、图片懒加载、任务拆解)及高频手段总结。同时提供性能优化黄金准则,如首屏资源控制在300KB内、关键接口响应≤200ms等,帮助开发者实现丝般流畅体验。
|
前端开发 JavaScript Shell
鸿蒙5开发宝藏案例分享---Web页面内点击响应时延分析
本文为鸿蒙开发者整理了Web性能优化的实战案例解析,结合官方文档深度扩展。内容涵盖点击响应时延核心指标(≤100ms)、性能分析工具链(如DevTools时间线、ArkUI Trace抓取)以及高频优化场景,包括递归函数优化、网络请求阻塞解决方案和setTimeout滥用问题等。同时提供进阶技巧,如首帧加速、透明动画陷阱规避及Web组件初始化加速,并通过优化前后Trace对比展示成果。最后总结了快速定位问题的方法与开发建议,助力开发者提升Web应用性能。
|
JSON 开发框架 自然语言处理
【HarmonyOS Next之旅】基于ArkTS开发(三) -> 兼容JS的类Web开发(三)
本文主要介绍了应用开发中的三大核心内容:生命周期管理、资源限定与访问以及多语言支持。在生命周期部分,详细说明了应用和页面的生命周期函数及其触发时机,帮助开发者更好地掌控应用状态变化。资源限定与访问章节,则聚焦于资源限定词的定义、命名规则及匹配逻辑,并阐述了如何通过 `$r` 引用 JS 模块内的资源。最后,多语言支持部分讲解了如何通过 JSON 文件定义多语言资源,使用 `$t` 和 `$tc` 方法实现简单格式化与单复数格式化,为全球化应用提供便利。
477 104
|
JavaScript 前端开发 API
【HarmonyOS Next之旅】基于ArkTS开发(三) -> 兼容JS的类Web开发(二)
本文介绍了HarmonyOS应用开发中的HML、CSS和JS语法。HML作为标记语言,支持数据绑定、事件处理、列表渲染等功能;CSS用于样式定义,涵盖尺寸单位、样式导入、选择器及伪类等特性;JS实现业务逻辑,包括ES6语法支持、对象属性、数据方法及事件处理。通过具体代码示例,详细解析了页面构建与交互的实现方式,为开发者提供全面的技术指导。
756 104
|
开发框架 编解码 JavaScript
【HarmonyOS Next之旅】基于ArkTS开发(三) -> 兼容JS的类Web开发(一)
该文档详细介绍了一个兼容JS的类Web开发范式的方舟开发框架,涵盖概述、文件组织、js标签配置及app.js等内容。框架采用HML、CSS、JavaScript三段式开发方式,支持单向数据绑定,适合中小型应用开发。文件组织部分说明了目录结构、访问规则和媒体文件格式;js标签配置包括实例名称、页面路由和窗口样式信息;app.js则描述了应用生命周期与对象管理。整体内容旨在帮助开发者快速构建基于方舟框架的应用程序。
549 102
|
开发框架 搜索推荐 数据可视化
Django框架适合开发哪种类型的Web应用程序?
Django 框架凭借其强大的功能、稳定性和可扩展性,几乎可以适应各种类型的 Web 应用程序开发需求。无论是简单的网站还是复杂的企业级系统,Django 都能提供可靠的支持,帮助开发者快速构建高质量的应用。同时,其活跃的社区和丰富的资源也为开发者在项目实施过程中提供了有力的保障。
1297 157
|
XML 安全 前端开发
一行代码搞定禁用 web 开发者工具
在如今的互联网时代,网页源码的保护显得尤为重要,特别是前端代码,几乎就是明文展示,很容易造成源码泄露,黑客和恶意用户往往会利用浏览器的开发者工具来窃取网站的敏感信息。为了有效防止用户打开浏览器的 Web 开发者工具面板,今天推荐一个不错的 npm 库,可以帮助开发者更好地保护自己的网站源码,本文将介绍该库的功能和使用方法。 功能介绍 npm 库名称:disable-devtool,github 路径:/theajack/disable-devtool。从 f12 按钮,右键单击和浏览器菜单都可以禁用 Web 开发工具。 🚀 一行代码搞定禁用 web 开发者工具 该库有以下特性: • 支持可配
1763 22

热门文章

最新文章