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,如需转载请自行联系原作者
目录
相关文章
|
10天前
|
关系型数据库 MySQL
web简易开发(二){html5+php实现文件上传及通过关键字搜索已上传图片)}
web简易开发(二){html5+php实现文件上传及通过关键字搜索已上传图片)}
|
1天前
|
编解码 数据库 计算机视觉
LabVIEW开发基于Web数字图像处理
LabVIEW开发基于Web数字图像处理
|
3天前
|
前端开发 JavaScript Java
Java与Web开发的结合:JSP与Servlet
Java与Web开发的结合:JSP与Servlet
8 0
|
4天前
|
存储 程序员 API
python web开发示例详解
python web开发示例详解
13 0
|
4天前
|
XML 前端开发 JavaScript
CSR(客户端渲染)和AJAX在Web开发中各自扮演不同的角色
【5月更文挑战第8天】CSR(客户端渲染)与AJAX在Web开发中各司其职。CSR提供初始HTML框架,通过JavaScript在浏览器端获取并渲染数据,提升交互性和响应速度。AJAX则实现页面局部更新,如实时搜索,不刷新页面即可获取数据。CSR可能因DOM操作多而引发性能问题,但可优化解决;AJAX适合频繁交互场景,提高响应性。两者在不同需求下各有优势,需按项目选择适用技术。
13 4
|
4天前
|
前端开发 搜索推荐 安全
AJAX和CSR(客户端渲染)是Web开发中常用的两种技术
【5月更文挑战第8天】AJAX提升用户体验,减轻服务器压力,但对搜索引擎不友好且增加开发复杂度,易引发安全问题。CSR提供快速响应和交互性,改善用户体验,但首屏加载慢,搜索引擎支持不足,同样面临安全挑战。两者各有适用场景,需按项目需求选择。
10 0
|
5天前
|
前端开发 JavaScript 开发者
新一代前端框架:革命性的Web开发利器
传统的前端框架在满足日益复杂的Web开发需求上逐渐显露出局限性,而新一代前端框架的出现,以其革命性的设计和功能,重新定义了Web开发的标准。本文将介绍这些新一代前端框架的特点和优势,并探讨它们在实际项目中的应用。
|
7天前
|
安全 测试技术 PHP
掌握现代Web开发:PHP 8的新特性与最佳实践
【5月更文挑战第5天】 在当今快速发展的网络世界中,PHP作为一种流行的服务器端脚本语言,持续地演化着。最新的PHP 8版本引入了一系列令人兴奋的新特性和性能改进,为开发者提供了更加强大和灵活的工具。本文将深入探讨PHP 8中的新特性,包括联合类型、名称参数、匹配表达式等,并分享一些最佳实践,帮助开发者提高代码质量,优化性能,并确保安全性。通过这些实用技巧和示例,您将能够构建更高效、更安全的PHP应用程序。
|
10天前
|
缓存 前端开发 Java
15:Servlet 3.0文件上传与下载-Java Web
15:Servlet 3.0文件上传与下载-Java Web
24 5
|
12天前
|
开发框架 JavaScript 前端开发
【JavaScript 与 TypeScript 技术专栏】TypeScript 在 Web 开发中的前沿应用
【4月更文挑战第30天】TypeScript在Web开发中日益重要,以其强大的类型系统提升代码质量,支持组件化开发,与React、Vue、Angular等框架良好集成。在大型项目管理中,TypeScript助于代码组织和优化,提高团队协作效率。此外,它提升开发体验,提供智能提示和错误检测。众多成功案例证明其前沿应用,未来将在Web开发领域持续发挥关键作用。