JSP上传图片并生成缩略图.docx

上传人:b****8 文档编号:11320878 上传时间:2023-02-26 格式:DOCX 页数:36 大小:28.38KB
下载 相关 举报
JSP上传图片并生成缩略图.docx_第1页
第1页 / 共36页
JSP上传图片并生成缩略图.docx_第2页
第2页 / 共36页
JSP上传图片并生成缩略图.docx_第3页
第3页 / 共36页
JSP上传图片并生成缩略图.docx_第4页
第4页 / 共36页
JSP上传图片并生成缩略图.docx_第5页
第5页 / 共36页
点击查看更多>>
下载资源
资源描述

JSP上传图片并生成缩略图.docx

《JSP上传图片并生成缩略图.docx》由会员分享,可在线阅读,更多相关《JSP上传图片并生成缩略图.docx(36页珍藏版)》请在冰豆网上搜索。

JSP上传图片并生成缩略图.docx

JSP上传图片并生成缩略图

先看看三

本例子使用了jspsmart组件进行上传,这里可以免费下载该组件

下载解压后,将jar包复制到 \WEB-INF\lib 目录后重启服务器,jspsmart即可正常使用了

1、uploadimage.jsp

<%@pagecontentType="text/html;charset=gb2312"language="java"import="java.io.*,java.awt.Image,java.awt.image.*,com.sun.image.codec.jpeg.*,

java.sql.*,com.jspsmart.upload.*,java.util.*,cn.oof.database.*,cn.oof.house.*"%>

<%

SmartUploadmySmartUpload=newSmartUpload();

longfile_size_max=4000000;

StringfileName2="",ext="",testvar="";

Stringurl="uploadfile/images/";     //应保证在根目录中有此目录的存在

//初始化

mySmartUpload.initialize(pageContext);

//只允许上载此类文件

try{

 mySmartUpload.setAllowedFilesList("jpg,gif");

//上载文件

 mySmartUpload.upload();

}catch(Exceptione){

%>

 

 alert("只允许上传.jpg和.gif类型图片文件");

 window.location=''''upfile.jsp'''';

 

<%

}

try{

   com.jspsmart.upload.FilemyFile=mySmartUpload.getFiles().getFile(0);

   if(myFile.isMissing()){%>

  

  alert("请先选择要上传的文件");

  window.location=''''upfile.jsp'''';

  

   <%}

   else{

     //StringmyFileName=myFile.getFileName();//取得上载的文件的文件名

  ext=myFile.getFileExt();     //取得后缀名

  intfile_size=myFile.getSize();    //取得文件的大小 

  Stringsaveurl="";

  if(file_size

   //更改文件名,取得当前上传时间的毫秒数值

   Calendarcalendar=Calendar.getInstance();

   Stringfilename=String.valueOf(calendar.getTimeInMillis());

   saveurl=request.getRealPath("/")+url;

   saveurl+=filename+"."+ext;         //保存路径

   myFile.saveAs(saveurl,mySmartUpload.SAVE_PHYSICAL);

   //out.print(filename);

//-----------------------上传完成,开始生成缩略图-------------------------   

   java.io.Filefile=newjava.io.File(saveurl);       //读入刚才上传的文件

   Stringnewurl=request.getRealPath("/")+url+filename+"_min."+ext; //新的缩略图保存地址

   Imagesrc=javax.imageio.ImageIO.read(file);                    //构造Image对象

   floattagsize=200;

   intold_w=src.getWidth(null);                                    //得到源图宽

   intold_h=src.getHeight(null);  

   intnew_w=0;

   intnew_h=0;                           //得到源图长

   inttempsize;

   floattempdouble;

   if(old_w>old_h){

    tempdouble=old_w/tagsize;

   }else{

    tempdouble=old_h/tagsize;

   }

   new_w=Math.round(old_w/tempdouble);

   new_h=Math.round(old_h/tempdouble);//计算新图长宽

   BufferedImagetag=newBufferedImage(new_w,new_h,BufferedImage.TYPE_INT_RGB);

   tag.getGraphics().drawImage(src,0,0,new_w,new_h,null);      //绘制缩小后的图

   FileOutputStreamnewimage=newFileOutputStream(newurl);         //输出到文件流

   JPEGImageEncoderencoder=JPEGCodec.createJPEGEncoder(newimage);      

   encoder.encode(tag);                                              //近JPEG编码

    newimage.close();   

  }

  else{

   out.print("");

   out.print("alert(''''上传文件大小不能超过"+(file_size_max/1000)+"K'''');");

   out.print("window.location=''''upfile.jsp;''''");

   out.print("");

  }

 }

}catch(Exceptione){

e.toString();

}

%>

2upload.htm

请选择上传的图片

 

   

请选择上传的图片

   

   

 

也谈一下文件上传

在这里看到很多讨论文件上传的文章,觉得各有利敝,有些只限于上传文件,而不能同时取得文本字段值,尤其是上传多个文件比较少,现本人做这个上传文件的类最多可支持上传255个文件,同时可取得文本字段值,请各位高手指正.

文件上传类:

MoqUploadBean.java 

package net.jspcn.tool;

import java.io.*;

import java.util.*;

import javax.servlet.*;

import javax.servlet.http.*;

/**

 *

 * Title:

 文件上传类

 * Description:

 既能对文件进行上传,又能取得输入框的值,最多可同时上传255个文件

 * Copyright:

 Copyright (c) 2002

 * Company:

 Tekson

 * @author 莫琼

 * @version 1.0

 */

public class UploadBean {

  private String[] sourceFile = new String[255];     //源文件名

  private String[] suffix = new String[255];         //文件后缀名

  private String canSuffix = ".gif.jpg.jpeg.png";    //可上传的文件后缀名

  private String objectPath = "c:

/";                 //目标文件目录

  private String[] objectFileName = new String[255]; //目标文件名

  private ServletInputStream sis = null;             //输入流

  private String[] description = new String[255];    //描述状态

  private long size = 100 * 1024;                    //限制大小

  private int count = 0;                             //已传输文件数目

  private byte[] b = new byte[4096];                 //字节流存放数组

  private boolean successful = true;

  private Hashtable fields = new Hashtable();

  public UploadBean() {

  }

  //设置上传文件的后缀名

  public void setSuffix(String canSuffix) {

    this.canSuffix = canSuffix;

  }

  //设置文件保存路径

  public void setObjectPath(String objectPath) {

    this.objectPath = objectPath;

  }

  //设置文件保存路径

  public void setSize(long maxSize) {

    this.size = maxSize;

  }

  //文件上传处理程序

  public void setSourceFile(HttpServletRequest request) throws IOException {

    sis = request.getInputStream();

    int a = 0;

    int k = 0;

    String s = "";

    while ( (a = sis.readLine(b, 0, b.length)) !

= -1) {

      s = new String(b, 0, a);

      if ( (k = s.indexOf("filename="")) !

= -1) {

        // 取得文件数据

        s = s.substring(k + 10);

        k = s.indexOf(""");

        s = s.substring(0, k);

        sourceFile[count] = s;

        k = s.lastIndexOf(".");

        suffix[count] = s.substring(k + 1);

        if (canTransfer(count)) {

          transferFile(count);

        }

        ++count;

      } else if ( (k = s.indexOf("name="")) !

= -1) {

        // 普通表单输入元素,获取输入元素名字

        String fieldName = s.substring(k+6, s.length()-3);

        sis.readLine(b, 0, b.length);

        StringBuffer fieldValue = new StringBuffer(b.length);

        while ( (a = sis.readLine(b, 0, b.length)) !

= -1) {

          s = new String(b, 0, a-2);

          if ( (b[0] == 45) && (b[1] == 45) && (b[2] == 45) && (b[3] == 45) && (b[4] == 45)) {

            break;

          } else {

            fieldValue.append(s);

          }

        }

        fields.put(fieldName, fieldValue.toString());

      }

      if (!

successful)

        break;

    }

  }

  //取得表单元素值

  public String getFieldValue(String fieldName) {

    if (fields == null || fieldName == null) {

      return null;

    }

    return (String) fields.get(fieldName);

  }

  //取得上传文件数

  public int getCount() {

    return count;

  }

  //取得目标路径

  public String getObjectPath() {

    return objectPath;

  }

  //取得源文件名

  public String[] getSourceFile() {

    return sourceFile;

  }

  //取得目标文件名

  public String[] getObjectFileName() {

    return objectFileName;

  }

  //取得上传状态描述

  public String[] getDescription() {

    return description;

  }

  //判断上传文件的类型

  private boolean canTransfer(int i) {

    suffix[i] = suffix[i].toLowerCase();

    //这个是用来传图片的,各位可以把后缀名改掉或者不要这个条件

    if (sourceFile[i].equals("") || (!

(canSuffix.indexOf("."+suffix[i])>=0))) {

      description[i] = "ERR:

 File suffix is wrong.";

      return false;

    }

    else {

      return true;

    }

  }

  //上传文件转换

  private void transferFile(int i) {

    String x = Long.toString(new java.util.Date().getTime());

    try {

      objectFileName[i] = x + "." + suffix[i];

      FileOutputStream out = new FileOutputStream(objectPath + objectFileName[i]);

      int a = 0;

      int k = 0;

      long hastransfered = 0; //标示已经传输的字节数

      String s = "";

      while ( (a = sis.readLine(b, 0, b.length)) !

= -1) {

        s = new String(b, 0, a);

        if ( (k = s.indexOf("Content-Type:

")) !

= -1) {

          break;

        }

      }

      sis.readLine(b, 0, b.length);

      while ( (a = sis.readLine(b, 0, b.length)) !

= -1) {

        s = new String(b, 0, a);

        if ( (b[0] == 45) && (b[1] == 45) && (b[2] == 45) && (b[3] == 45) && (b[4] == 45)) {

          break;

        }

        out.write(b, 0, a);

        hastransfered += a;

        if (hastransfered >= size) {

          description[count] = "ERR:

 The file " + sourceFile[count] +

              " is too large to transfer. The whole process is interrupted.";

          successful = false;

          break;

        }

      }

      if (successful) {

        description[count] = "Right:

 The file " + sourceFile[count] +

            " has been transfered successfully.";

      }

      out.close();

      if (!

successful) {

        sis.close();

        File tmp = new File(objectPath + objectFileName[count]);

        tmp.delete();

      }

    }

    catch (IOException ioe) {

      description[i] = ioe.toString();

    }

  }

  public static void main(String[] args) {

    System.out.println("Test OK");

  }

}

文件上传调用:

MoqUpload.jsp

〈%@ page contentType="text/html; charset=GB2312" %>

〈html>

〈head>

〈title>文件上载〈/title>

〈/head>

〈body>

〈form action="MoqUploadSubmit.jsp" enctype="MULTIPART/FORM-DATA" method="post">

作者姓名:

〈input type="text" name="Author" />

〈br />

公司名称:

〈input type="text" name="Company" />

〈br />

文件描述:

〈input type="text" name="Comment" />

〈br />

选择文件1:

〈input type="file" name="filename1" />

〈br />

选择文件2:

〈input type="file" name="filename2" />

〈br />

选择文件3:

〈input type="file" name="filename3" />

〈br />

选择文件4:

〈input type="file" name="filename4" />

〈br />

〈input type="submit" value="上载" />

〈/form>

〈/body>

〈/html>

文件上传提交:

MoqUploadSubmit.jsp

〈%@ page contentType="text/html;charset=gb2312"%>

〈jsp:

useBean id="fileBean" 

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 高等教育 > 经济学

copyright@ 2008-2022 冰豆网网站版权所有

经营许可证编号:鄂ICP备2022015515号-1