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, 08192)) != -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.10.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), 00null);
             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,如需转载请自行联系原作者
上一篇:Confluence 6 考虑使用自定义 CSS


下一篇:Java 性能要点:自动装箱/ 拆箱 (Autoboxing / Unboxing)