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,如需转载请自行联系原作者
目录
相关文章
|
21天前
|
监控 JavaScript 前端开发
《理解 WebSocket:Java Web 开发的实时通信技术》
【4月更文挑战第4天】WebSocket是Java Web实时通信的关键技术,提供双向持久连接,实现低延迟、高效率的实时交互。适用于聊天应用、在线游戏、数据监控和即时通知。开发涉及服务器端实现、客户端连接及数据协议定义,注意安全、错误处理、性能和兼容性。随着实时应用需求增加,WebSocket在Java Web开发中的地位将更加重要。
|
1月前
|
Web App开发 前端开发 开发工具
介绍Web开发的基础知识
介绍Web开发的基础知识
29 7
|
1月前
|
存储 资源调度 应用服务中间件
浅谈本地开发好的 Web 应用部署到 ABAP 应用服务器上的几种方式
浅谈本地开发好的 Web 应用部署到 ABAP 应用服务器上的几种方式
26 0
|
1月前
|
存储 前端开发 JavaScript
从前端到后端,探索现代Web开发技术
本文探索了现代Web开发技术的各个方面,包括前端和后端开发以及多种编程语言的应用。通过对JavaScript、Java、Python、C、PHP和Go等语言的介绍,深入探讨了前端和后端开发的基本原理和常用工具。同时,还涵盖了数据库技术在Web开发中的重要性和应用场景。无论你是初学者还是有经验的开发者,本文都能为你提供全面的视角和实用的知识,帮助你在Web开发领域取得更好的成果。
|
1月前
|
缓存 关系型数据库 API
后端开发:构建高效、可扩展的Web应用程序的关键
后端开发:构建高效、可扩展的Web应用程序的关键
21 0
|
7天前
|
JSON Java fastjson
Spring Boot 底层级探索系列 04 - Web 开发(2)
Spring Boot 底层级探索系列 04 - Web 开发(2)
15 0
|
7天前
|
安全 编译器 PHP
PHP 8.1版本发布:引领Web开发新潮流
PHP编程语言一直是Web开发的主力军,而最新发布的PHP 8.1版本则为开发者们带来了更多创新和便利。本文将介绍PHP 8.1版本的主要特性,包括更快的性能、新的语言功能和增强的安全性,以及如何利用这些功能来提升Web应用程序的质量和效率。
|
10天前
|
PHP
web简易开发——通过php与HTML+css+mysql实现用户的登录,注册
web简易开发——通过php与HTML+css+mysql实现用户的登录,注册
|
10天前
|
前端开发 数据挖掘 API
使用Python中的Flask框架进行Web应用开发
【4月更文挑战第15天】在Python的Web开发领域,Flask是一个备受欢迎的轻量级Web框架。它简洁、灵活且易于扩展,使得开发者能够快速地构建出高质量的Web应用。本文将深入探讨Flask框架的核心特性、使用方法以及在实际开发中的应用。
|
19天前
|
安全 前端开发 Java
Java Web开发知识点学习总结
Java Web开发涉及Java基础、Servlet、JSP、数据库操作(SQL+JDBC)、MVC设计模式、Spring框架、Hibernate ORM、Web服务(SOAP&RESTful)、安全认证(HTTP Basic/Digest/OAuth)及性能优化(缓存、异步、负载均衡)。
17 3