用java完成图片多张批量上传的功能,还有就是后台的应该怎么处理上传的照片。
环境准备
1. 下载并安装Tomcat(已经有很多关于Tomcat安装以及使用的文章,在这里不再介绍);
2. 下载File upload的jar包commons-fileupload-1.0-beta-1.jar,并将该文件拷贝到{$TOMCAT}/common/lib目录下(其中{$TOMCAT}为Tomcat的安装目录);
3. 由于Fileupload子项目同时要用到另外一个项目commons-Beanutils,所以必须下载Beanutils,并将解压后的文件commons-beanutils.jar拷贝到{$TOMCAT}/common/lib目录下。
开发文件上传页面
文件上传的界面如图1所示。为了增加效率我们设计了三个文件域,同时上传三个文件。
图1 文件上传界面
页面的HTML代码如下:
html
head
title文件上传演示/title
/head
body bgcolor=“#FFFFFF”text=“#000000” leftmargin=“0”topmargin=“40”marginwidth=“0” marginheight=“0”
center
h1文件上传演示/h1
form name=“uploadform”method=“POST” action=“save.jsp”ENCTYPE=“multipart/form-data”
table border=“1”width=“450”cellpadding=“4” cellspacing=“2”bordercolor=“#9BD7FF”
trtd width=“100%”colspan=“2”
文件1:input name=“file1”size=“40”type=“file”
/td/tr
trtd width=“100%”colspan=“2”
文件2:input name=“file2”size=“40”type=“file”
/td/tr
trtd width=“100%”colspan=“2”
文件3:input name=“file3”size=“40”type=“file”
/td/tr
/table
br/br/
table
trtd align=“center”input name=“upload” type=“submit”value=“开始上传”//td/tr
/table
/form
/center
/body
/html
代码中要特别注意的是黑体处。必须保证表单的ENCTYPE属性值为multipart/form-data,这样浏览器才能正确执行上传文件的操作。
处理上传文件信息
由于本文主要是讲述如何使用Commons-fileupload,所以为了便于修改、调试,上传文件的保存使用一个JSP文件来进行处理。我们将浏览器上传来的所有文件保存在一个指定目录下并在页面上显示所有上传文件的详细信息。保存页面处理结果见图2所示。
图2 保存页面
下面来看看save.jsp的代码:
%
/**
* 演示文件上传的处理
* @author a href=“mailto:winter.lau@163.com”Winter Lau/a
* @version $Id: save.jsp,v 1.00 2003/03/01 10:10:15
*/
%
%@ page language=“java”contentType=“text/html;charset=GBK”%
%@ page import=“java.util.*”%
%@ page import=“org.apache.commons.fileupload.*”%
html
head
title保存上传文件/title
/head
%
String msg = “”;
FileUpload fu = new FileUpload();
// 设置允许用户上传文件大小,单位:字节
fu.setSizeMax(10000000);
// maximum size that will be stored in memory?
// 设置最多只允许在内存中存储的数据,单位:字节
fu.setSizeThreshold(4096);
// 设置一旦文件大小超过getSizeThreshold()的值时数据存放在硬盘的目录
fu.setRepositoryPath(“C:\\TEMP”);
//开始读取上传信息
List fileItems = fu.parseRequest(request);
%
body bgcolor=“#FFFFFF”text=“#000000” leftmargin=“0”topmargin=“40”marginwidth=“0” marginheight=“0”
font size=“6”color=“blue”文件列表:/font
center
table cellpadding=0 cellspacing=1 border=1 width=“100%”
tr
td bgcolor=“#008080”文件名/td
td bgcolor=“#008080”大小/td
/tr
%
// 依次处理每个上传的文件
Iterator iter = fileItems.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
//忽略其他不是文件域的所有表单信息
if (!item.isFormField()) {
String name = item.getName();
long size = item.getSize();
if((name==null||name.equals(“”)) size==0)
continue;
%
tr
td%=item.getName()%/td
td%=item.getSize()%/td
/tr
%
//保存上传的文件到指定的目录
name = name.replace(‘:’,‘_’);
name = name.replace(‘\\’,‘_’);
item.write(“F:\\”+ name);
}
}
%
/table
br/br/
a href=“upload.html”返回上传页面/a
/center
/body
/html
在这个文件中需要注意的是FileUpload对象的一些参数值的意义,如下面代码所示的三个参数sizeMax、sizeThreshold、repositoryPath:
FileUpload fu = new FileUpload();
// 设置允许用户上传文件大小,单位:字节
fu.setSizeMax(10000000);
// maximum size that will be stored in memory?
// 设置最多只允许在内存中存储的数据,单位:字节
fu.setSizeThreshold(4096);
// 设置一旦文件大小超过getSizeThreshold()的值时数据存放在硬盘的目录
fu.setRepositoryPath(“C:\\TEMP”);
这3个参数的意义分别为:
SizeMax 用来设置上传文件大小的最大值,一旦用户上传的文件大小超过该值时将会抛出一个FileUploadException异常,提示文件太大;
SizeThreshold 设置内存中缓冲区的大小,一旦文件的大小超过该值的时候,程序会自动将其它数据存放在repositoryPath指定的目录下作为缓冲。合理设置该参数的值可以保证服务器稳定高效的运行;
RepositoryPath 指定缓冲区目录。
使用注意事项
从实际应用的结果来看该模块能够稳定高效的工作。其中参数SizeThreshold的值至关重要,设置太大会占用过多的内存,设置太小会频繁使用硬盘作为缓冲以致牺牲性能。因此,设置该值时要根据用户上传文件大小分布情况来设定。例如大部分文件大小集中在100KB左右,则可以使用100KB作为该参数的值,当然了再大就不合适了。使用commons-fileupload来处理HTTP文件上传的功能模块很小,但是值得研究的东西很多。
java web开发,上传图片并读取
java web开发中,使用文件操作类来上传图片并读取,如下代码:
* @desc: 图片处理工具
* @author: bingye
* @createTime: 2015-3-17 下午04:25:32
* @version: v1.0
*/
public class ImageUtil {
/**
* 将图片写到客户端
* @author: bingye
* @createTime: 2015-3-17 下午04:36:04
* @history:
* @param image
* @param response void
*/
public static void writeImage(byte[] image,HttpServletResponse response){
if(image==null){
return;
}
byte[] buffer=new byte[1024];
InputStream is=null;
OutputStream os=null;
try {
is=new ByteArrayInputStream(image);
os=response.getOutputStream();
while(is.read(buffer)!=-1){
os.write(buffer);
os.flush();
}
} catch (IOException e) {
e.printStackTrace();
} finally{
try {
if(is!=null){is.close();}
if(os!=null){os.close();}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 获取指定路劲图片
* @author: bingye
* @createTime: 2015-3-21 上午10:50:44
* @param filePath
* @param response void
*/
public static void writeImage(String filePath,HttpServletResponse response){
File imageFile=new File(filePath);
if(imageFile!=null imageFile.exists()){
byte[] buffer=new byte[1024];
InputStream is=null;
OutputStream os=null;
try {
is=new FileInputStream(imageFile);
os=response.getOutputStream();
while(is.read(buffer)!=-1){
os.write(buffer);
os.flush();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
try {
if(is!=null){is.close();}
if(os!=null){os.close();}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 图片上传到文件夹
* @author: bingye
* @createTime: 2015-3-20 下午08:07:25
* @param file
* @param savePath
* @return boolean
*/
public static ResultDto uploadToLocal(CommonsMultipartFile file,String savePath){
if(file!=null !file.isEmpty()){
//获取文件名称
String fileName=file.getOriginalFilename();
//获取后缀名
String suffixName=fileName.substring(fileName.indexOf(".")+1);
//新名称
String newFileName=System.currentTimeMillis()+"."+suffixName;
//新文件路劲
String filePath=savePath+newFileName;
//获取存储文件路径
File fileDir=new File(savePath);
if(!fileDir.exists()){
//如果文件夹没有:新建
fileDir.mkdirs();
}
FileOutputStream fos=null;
try {
fos=new FileOutputStream(filePath);
fos.write(file.getBytes());
fos.flush();
return ResultUtil.success("UPLOAD_SUCCESS", URLEncoder.encode(newFileName,"utf-8"));
} catch (Exception e) {
e.printStackTrace();
return ResultUtil.fail("UPLOAD_ERROR");
} finally{
try {
if(fos!=null){
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
return ResultUtil.fail("UPLOAD_ERROR");
}
}
}
return ResultUtil.fail("UPLOAD_ERROR");
}
}
请问用Java 如何实现图片上传功能 ?
我有一段上传图片的代码,并且可以根据实际,按月或按天等,生成存放图片的文件夹
首先在JSP上放一个FILE的标签这些我都不说了,你也一定明白,我直接把处理过程给你发过去
我把其中存到数据库中的内容删除了,你改一下就能用
/**
*
* 上传图片
* @param servlet
* @param request
* @param response
* @return
* @throws Exception
*/
//这里我是同步上传的,你随意
public synchronized String importPic(HttpServlet servlet, HttpServletRequest request,HttpServletResponse response) throws Exception {
SimpleDateFormat formatDate = new SimpleDateFormat("yyyyMM");
Date nowtime=new Date();
String formatnowtime=formatDate.format(nowtime);
File root = new File(request.getRealPath("/")+"uploadfile/images/"+formatnowtime+"/"); //应保证在根目录中有此目录的存在 如果没有,下面则上创建新的文件夹
if(!root.isDirectory())
{
System.out.println("创建新文件夹成功"+formatnowtime);
root.mkdir();
}
int returnflag = 0;
SmartUpload mySmartUpload =new SmartUpload();
int file_size_max=1024000;
String ext="";
String url="uploadfile/images/"+formatnowtime+"/";
// 只允许上载此类文件
try{
// 初始化
mySmartUpload.initialize(servlet.getServletConfig(),request,response);
mySmartUpload.setAllowedFilesList("jpg,gif,bmp,jpeg,png,JPG");
// 上载文件
mySmartUpload.upload();
} catch (Exception e){
response.sendRedirect()//返回页面
}
com.jspsmart.upload.File myFile = mySmartUpload.getFiles().getFile(0);
if (myFile.isMissing()){ //没有选择图片做提示!
returnflag = 3;
}else{
String myFileName=myFile.getFileName(); //取得上载的文件的文件名
ext= myFile.getFileExt(); //取得后缀名
if(ext.equals("jpg")||ext.equals("gif")||ext.equals("bmp")||ext.equals("jpeg")||ext.equals("png")||ext.equals("JPG")){ //jpeg,png不能上传!)
int file_size=myFile.getSize(); //取得文件的大小
String saveurl="";
if(file_sizefile_size_max){
try{
//我上面说到,把操作数据库的代友删除了,这里就应该是判断,你的图片是不是已经存在了,存在要怎么处理,不存在要怎么处了,就是你的事了 }
//更改文件名,取得当前上传时间的毫秒数值
Calendar calendar = Calendar.getInstance();
//String filename = String.valueOf(calendar.getTimeInMillis());
String did = contractBean.getMaxSeq("MULTIMEDIA_SEQ");
String filename = did;
String flag = "0";
String path = request.getRealPath("/")+url;
String ename = myFile.getFileExt();
//.toLowerCase()转换大小写
saveurl=request.getRealPath("/")+url;
saveurl+=filename+"."+ext; //保存路径
myFile.saveAs(saveurl,mySmartUpload.SAVE_PHYSICAL);
//将图片信息插入到数据库中
// ------上传完成,开始生成缩略图-----
java.io.File file = new java.io.File(saveurl); //读入刚才上传的文件
String newurl=request.getRealPath("/")+url+filename+"_min."+ext; //新的缩略图保存地址
Image src = javax.imageio.ImageIO.read(file); //构造Image对象
float tagsize=200;
int old_w=src.getWidth(null);
int old_h=src.getHeight(null);
int new_w=0;
int new_h=0;
int tempsize;
float tempdouble;
if(old_wold_h){
tempdouble=old_w/tagsize;
}else{
tempdouble=old_h/tagsize;
}
// new_w=Math.round(old_w/tempdouble);
// new_h=Math.round(old_h/tempdouble);//计算新图长宽
new_w=150;
new_h=110;//计算新图长宽
BufferedImage tag = new BufferedImage(new_w,new_h,BufferedImage.TYPE_INT_RGB);
tag.getGraphics().drawImage(src,0,0,new_w,new_h,null); //绘制缩小后的图
FileOutputStream newimage=new FileOutputStream(newurl); //输出到文件流
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(newimage);
encoder.encode(tag); //近JPEG编码
newimage.close();
returnflag = 1;
}else{
returnflag = 0;
System.out.println("('上传文件大小不能超过"+(file_size_max/1000)+"K');");
}
}else{
returnflag = 2;
}
}
response.sendRedirect();
return "11";
}
java 中如何向服务器上传图片
我们使用一些已有的组件帮助我们实现这种上传功能。
常用的上传组件:
Apache 的 Commons FileUpload
JavaZoom的UploadBean
jspSmartUpload
以下,以FileUpload为例讲解
1、在jsp端
form id="form1" name="form1" method="post" action="servlet/fileServlet" enctype="multipart/form-data"
要注意enctype="multipart/form-data"
然后只需要放置一个file控件,并执行submit操作即可
input name="file" type="file" size="20"
input type="submit" name="submit" value="提交"
2、web端
核心代码如下:
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List items = upload.parseRequest(request);
Iterator itr = items.iterator();
while (itr.hasNext()) {
FileItem item = (FileItem) itr.next();
if (item.isFormField()) {
System.out.println("表单参数名:" + item.getFieldName() + ",表单参数值:" + item.getString("UTF-8"));
} else {
if (item.getName() != null !item.getName().equals("")) {
System.out.println("上传文件的大小:" + item.getSize());
System.out.println("上传文件的类型:" + item.getContentType());
System.out.println("上传文件的名称:" + item.getName());
File tempFile = new File(item.getName());
File file = new File(sc.getRealPath("/") + savePath, tempFile.getName());
item.write(file);
request.setAttribute("upload.message", "上传文件成功!");
}else{
request.setAttribute("upload.message", "没有选择上传文件!");
}
}
}
}catch(FileUploadException e){
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
request.setAttribute("upload.message", "上传文件失败!");
}
request.getRequestDispatcher("/uploadResult.jsp").forward(request, response);
}
以上内容为新媒号(sinv.com.cn)为大家提供!新媒号,坚持更新大家所需的互联网后端知识。希望您喜欢!
版权申明:新媒号所有作品(图文、音视频)均由用户自行上传分享,仅供网友学习交流,不声明或保证其内容的正确性,如发现本站有涉嫌抄袭侵权/违法违规的内容。请发送邮件至 k2#88.com(替换@) 举报,一经查实,本站将立刻删除。