java图片文件上传|java怎样上传图片(写个例子谢谢);

java图片文件上传|java怎样上传图片(写个例子谢谢);的第1张示图

⑴ 怎么用java实现图片上传

下面这是servlet的内容:package demo;import java.io.File;import java.io.IOException;import java.io.PrintWriter;import java.util.List;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.commons.fileupload.FileItem;import org.apache.commons.fileupload.ProgressListener;import org.apache.commons.fileupload.disk.DiskFileItemFactory;import org.apache.commons.fileupload.servlet.ServletFileUpload;public class DemoServlet extends HttpServlet {private static final String UPLOAD_DIRECTORY = "upload";private static final int MEMORY_THRESHOLD = 1024 * 1024 * 3; // 3MBprivate static final int MAX_FILE_SIZE = 1024 * 1024 * 40; // 40MBprivate static final int MAX_REQUEST_SIZE = 1024 * 1024 * 50; // 50MBprotected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {DiskFileItemFactory factory=new DiskFileItemFactory();ServletFileUpload sfu=new ServletFileUpload(factory);sfu.setHeaderEncoding("UTF-8");sfu.setProgressListener(new ProgressListener() {public void update(long pBytesRead, long pContentLength, int pItems) {System.out.println("文件大小为:"+pContentLength+",当前已处理:"+pBytesRead);}});//判断提交上来的数据是否是上传表单的数据if(!ServletFileUpload.isMultipartContent(request)){PrintWriter writer= response.getWriter();writer.println("Error:表单必须包含 enctype=multipart/form-data");writer.flush();return;}factory.setSizeThreshold(MEMORY_THRESHOLD);//设置临时储存目录factory.setRepository(new File(System.getProperty("java.io.tmpdir")));//设置最大文件上传值sfu.setFileSizeMax(MAX_FILE_SIZE);//设置最大请求值(包含文件和表单数据)sfu.setSizeMax(MAX_REQUEST_SIZE);String uploadpath=getServletContext().getRealPath("./")+ File.separator+UPLOAD_DIRECTORY;File file=new File(uploadpath);if(!file.exists()){file.mkdir();}try {List<FileItem> formItems = sfu.parseRequest(request);if(formItems!=null&&formItems.size()>0){for(FileItem item:formItems){if(!item.isFormField()){String fileName=new File(item.getName()).getName();String filePath=uploadpath+File.separator+fileName;File storeFile=new File(filePath);System.out.println(filePath);item.write(storeFile);request.setAttribute("message", "文件上传成功!");}}}} catch (Exception e) {request.setAttribute("message", "错误信息:"+e.getMessage());}getServletContext().getRequestDispatcher("/demo.jsp").forward(request, response);}}下面是jsp的内容,jsp放到webapp下,如果想放到WEB-INF下就把servlet里转发的路径改一下:<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Insert title here</title></head><body><form action="demo.do" enctype="multipart/form-data" method="post"><input type="file" name="file1" /><%String message = (String) request.getAttribute("message");%><%=message%><input type="submit" value="提交"/></form></body></html>这段代码可以实现普通的文件上传,有大小限制,上传普通的图片肯定没问题,别的一些小的文件也能传

⑵ java怎么上传图片

使用Commons-FileUpload 上传文件

Struts 的文件上传

jspSmartUpload上传文件

⑶ java怎样上传图片(写个例子谢谢);

我有一段上传图片的代码,并且可以根据实际,按月或按天等,生成存放图片的文件夹首先在JSP上放一个FILE的标签这些我都不说了,你也一定明白,我直接把处理过程给你发过去我把其中存到数据库中的内容删除了,你改一下就能用/** * * 上传图片 * @param servlet * @param request * @param response * @return * @throws Exception */ //这里我是同步上传的,你随意public synchronized String importPic(HttpServlet servlet, HttpServletRequest request,HttpServletResponse response) throws Exception {SimpleDate()Format formatDate() = new SimpleDate()Format("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_size<file_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_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);//计算新图长宽 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上传图片

/** * */package net.hlj.chOA.action;import java.io.File;import java.io.UnsupportedEncodingException;import java.sql.SQLException;import java.text.SimpleDateFormat;import java.util.Date;import java.util.Iterator;import java.util.List;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import net.hlj.chOA..DangAnDao;import net.hlj.chOA..LogDao;import net.hlj.chOA..ZiYuanDao;import net.hlj.chOA.model.DangAn;import net.hlj.chOA.model.User;import net.hlj.chOA.model.ZiYuan;import net.hlj.chOA.util.GetId;import org.apache.commons.fileupload.FileItem;import org.apache.commons.fileupload.FileUploadException;import org.apache.commons.fileupload.disk.DiskFileItemFactory;import org.apache.commons.fileupload.servlet.ServletFileUpload;import org.apache.struts.action.ActionForm;import org.apache.struts.action.ActionForward;import org.apache.struts.action.ActionMapping;import org.apache.struts.actions.DispatchAction;/** * @author lcy * */public class ZiYuanAction extends DispatchAction { public ActionForward addZiYuan(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { String title = ""; String fileupload=""; SimpleDateFormat fmt = new SimpleDateFormat("yyMMddhhssmmSSS"); Date now = new Date(); String date = fmt.format(now); String filePath = request.getSession().getServletContext().getRealPath( "/"); String uploadPath = filePath + "upload\\uploadZiYuan\\"; String tempPath = filePath + "upload\\uploadZiYuan\\" + "uploadTemp"; String suffix = null; if (!new File(uploadPath).isDirectory()) { new File(uploadPath).mkdirs(); } DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(4194304);// 设置初始化内存,如果上传的文件超过该大小,将不保存到内存,而且硬盘中(单位:byte) File fileTemp = new File(tempPath);// 建立临时目录 fileTemp.mkdir(); factory.setRepository(fileTemp); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(4194304);// 设置客户端最大上传,-1为无限大(单位:byte) try { List<FileItem> items = upload.parseRequest(request); Iterator<FileItem> i = items.iterator(); String[] rightType = {".gif", ".jpeg", ".doc", ".xls", ".pdf", ".txt", ".rar" }; while (i.hasNext()) { FileItem fi = (FileItem) i.next(); if (fi.isFormField()) { try { if (fi.getFieldName().equals("title")) { title = fi.getString("UTF-8"); } } catch (UnsupportedEncodingException e) { log.error(e.getMessage(), e); } } else { String fileName = fi.getName(); int l = fileName.length(); if (!fileName.equals("")) { int pos = fileName.lastIndexOf("."); // suffix = fileName.substring(l – 4, l); suffix = fileName.substring(pos, l); boolean result = false; String ext = fileName.substring(fileName .lastIndexOf(".")); for (int j = 0; j < rightType.length; j++) { if (ext.toLowerCase().equals(rightType[j])) { result = true; break; } } if (!result) { request.setAttribute("error", "上传文件类型有误!"); return mapping.findForward("addZiyuan"); } // if (!suffix.equalsIgnoreCase(".jpg") && // !suffix.equalsIgnoreCase(".gif") // && !suffix.equalsIgnoreCase(".png") && // !suffix.equalsIgnoreCase(".bmp")) { // request.setAttribute("message", "上传文件类型有误!"); // return mapping.findForward("danganList"); // } if (fileName != null) { File savedFile = new File(uploadPath, date + suffix); try { fi.write(savedFile); fileupload = "upload/uploadZiYuan/" + date + suffix; } catch (Exception e) { log.error(e.getMessage(), e); } } } } } } catch (FileUploadException e) { log.error(e.getMessage(), e); } ZiYuan zy=new ZiYuan(); zy.setTitle(title); zy.setUpload(fileupload); ZiYuanDao zyDao=new ZiYuanDao(); try { zyDao.addZiYuan(zy, this.servlet.getServletContext()); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } LogDao lDao=new LogDao(); //删除操做添加日志 isDel 0是增加,1是删除,2是修改,3是审批 User user1 =(User)request.getSession().getAttribute("userBean"); String ip=request.getLocalAddr(); int id=GetId.getId("ziyuan", this.servlet.getServletContext()); try { lDao.addLogMe("ziyuan", id , ip, user1.getName(), user1.getId(), 0, this.servlet.getServletContext()); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return mapping.findForward("ziyuanList"); } public ActionForward deleteZiYuan(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { String[] ids= request.getParameterValues("id"); ZiYuanDao zyDao=new ZiYuanDao(); LogDao lDao=new LogDao(); for(int i=0;i<ids.length;i++){ try { zyDao.deleteZiYuan(Integer.parseInt(ids[i]), this.servlet.getServletContext()); } catch (NumberFormatException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } User user =(User)request.getSession().getAttribute("userBean"); String ip=request.getLocalAddr(); try { lDao.addLogMe("tbl_users",Integer.parseInt(ids[i]), ip, user.getName(), user.getId(), 1, this.servlet.getServletContext()); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return mapping.findForward("ziyuanList"); } public ActionForward updateZiYuan(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws NumberFormatException, SQLException { String id=""; String title = ""; String fileupload=""; SimpleDateFormat fmt = new SimpleDateFormat("yyMMddhhssmmSSS"); Date now = new Date(); String date = fmt.format(now); String filePath = request.getSession().getServletContext().getRealPath( "/"); String uploadPath = filePath + "upload\\uploadZiYuan\\"; String tempPath = filePath + "upload\\uploadZiYuan\\" + "uploadTemp"; String suffix = null; if (!new File(uploadPath).isDirectory()) { new File(uploadPath).mkdirs(); } DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(4194304);// 设置初始化内存,如果上传的文件超过该大小,将不保存到内存,而且硬盘中(单位:byte) File fileTemp = new File(tempPath);// 建立临时目录 fileTemp.mkdir(); factory.setRepository(fileTemp); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(4194304);// 设置客户端最大上传,-1为无限大(单位:byte) try { List<FileItem> items = upload.parseRequest(request); Iterator<FileItem> i = items.iterator(); String[] rightType = {".gif", ".jpeg", ".doc", ".xls", ".pdf", ".txt", ".rar" }; while (i.hasNext()) { FileItem fi = (FileItem) i.next(); if (fi.isFormField()) { try { if (fi.getFieldName().equals("title")) { title = fi.getString("UTF-8"); } if (fi.getFieldName().equals("id")) { id = fi.getString("UTF-8"); } } catch (UnsupportedEncodingException e) { log.error(e.getMessage(), e); } } else { String fileName = fi.getName(); int l = fileName.length(); if (!fileName.equals("")) { int pos = fileName.lastIndexOf("."); // suffix = fileName.substring(l – 4, l); suffix = fileName.substring(pos, l); boolean result = false; String ext = fileName.substring(fileName .lastIndexOf(".")); for (int j = 0; j < rightType.length; j++) { if (ext.toLowerCase().equals(rightType[j])) { result = true; break; } } if (!result) { request.setAttribute("error", "上传文件类型有误!"); request.setAttribute("id", id); return mapping.findForward("selectZiyuan"); } // if (!suffix.equalsIgnoreCase(".jpg") && // !suffix.equalsIgnoreCase(".gif") // && !suffix.equalsIgnoreCase(".png") && // !suffix.equalsIgnoreCase(".bmp")) { // request.setAttribute("message", "上传文件类型有误!"); // return mapping.findForward("danganList"); // } if (fileName != null) { File savedFile = new File(uploadPath, date + suffix); try { fi.write(savedFile); fileupload = "upload/uploadZiYuan/" + date + suffix; } catch (Exception e) { log.error(e.getMessage(), e); } } }else{ //这里写如果用户没有重写添加附件则保持原来的附件 ZiYuanDao zyDao = new ZiYuanDao(); ZiYuan zy=(ZiYuan)zyDao.selectZiYuanById(Integer.parseInt(id), this.servlet.getServletContext()).get(0); fileupload=zy.getUpload(); } } } } catch (FileUploadException e) { log.error(e.getMessage(), e); } ZiYuan zy=new ZiYuan(); zy.setId(Integer.parseInt(id)); zy.setTitle(title); zy.setUpload(fileupload); ZiYuanDao zyDao=new ZiYuanDao(); try { zyDao.updateZiYuan(zy, this.servlet.getServletContext()); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } LogDao lDao=new LogDao(); //删除操做添加日志 isDel 0是增加,1是删除,2是修改,3是审批 User user1 =(User)request.getSession().getAttribute("userBean"); String ip=request.getLocalAddr(); try { lDao.addLogMe("ziyuan", Integer.parseInt(id) , ip, user1.getName(), user1.getId(), 2, this.servlet.getServletContext()); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return mapping.findForward("ziyuanList"); }}

⑸ 用java怎么上传图片到项目指定的文件夹

代码如下:import java.io.*; /** * 复制文件夹或文件夹 */ public class CopyDirectory { // 源文件夹 static String url1 = "f:/photos"; // 目标文件夹 static String url2 = "d:/tempPhotos"; public static void main(String args[]) throws IOException { // 创建目标文件夹 (new File(url2)).mkdirs(); // 获取源文件夹当前下的文件或目录 File[] file = (new File(url1)).listFiles(); for (int i = 0; i < file.length; i++) { if (file[i].isFile()) { // 复制文件 File(file[i],new File(url2+file[i].getName())); } if (file[i].isDirectory()) { // 复制目录 String sourceDir=url1+File.separator+file[i].getName(); String targetDir=url2+File.separator+file[i].getName(); Directiory(sourceDir, targetDir); } } } // 复制文件 public static void File(File sourceFile,File targetFile) throws IOException{ // 新建文件输入流并对它进行缓冲 FileInputStream input = new FileInputStream(sourceFile); BufferedInputStream inBuff=new BufferedInputStream(input); // 新建文件输出流并对它进行缓冲 FileOutputStream output = new FileOutputStream(targetFile); BufferedOutputStream outBuff=new BufferedOutputStream(output); // 缓冲数组 byte[] b = new byte[1024 * 5]; int len; while ((len =inBuff.read(b)) != -1) { outBuff.write(b, 0, len); } // 刷新此缓冲的输出流 outBuff.flush(); //关闭流 inBuff.close(); outBuff.close(); output.close(); input.close(); } // 复制文件夹 public static void Directiory(String sourceDir, String targetDir) throws IOException { // 新建目标目录 (new File(targetDir)).mkdirs(); // 获取源文件夹当前下的文件或目录 File[] file = (new File(sourceDir)).listFiles(); for (int i = 0; i < file.length; i++) { if (file[i].isFile()) { // 源文件 File sourceFile=file[i]; // 目标文件 File targetFile=new File(new File(targetDir).getAbsolutePath() +File.separator+file[i].getName()); File(sourceFile,targetFile); } if (file[i].isDirectory()) { // 准备复制的源文件夹 String dir1=sourceDir + "/" + file[i].getName(); // 准备复制的目标文件夹 String dir2=targetDir + "/"+ file[i].getName(); Directiory(dir1, dir2); } } } }

⑹ Java中如何图片异步上传

在java中要实现异步上传要提前做好准备,对于文件上传,浏览器在上传的过程中是将文件以流的形式提交到服务器端的,如果直接使用Servlet获取上传文件的输入流然后再解析里面的请求参数是比较麻烦,所以一般选择采用apache的开源工具common-fileupload这个文件上传组件。这个common-fileupload上传组件的jar包可以去apache官网上面下载,也可以在struts的lib文件夹下面找到,struts上传的功能就是基于这个实现的。common-fileupload是依赖于common-io这个包的,所以还需要下载这个包。剩下的就是js文件的导入了,我导入了以下文件:<script type="text/javascript" src="lib/Js/jquery.js"></script><script ltype="text/javascript" src="/js/ajaxfileupload.js"></script>在页面中的写法:div class="controls"><span class="btn green fileinput-button"><i class="icon-plus icon-white"></i><span>上传照片</span><input id="fileToUpload" name="myfiles" type="file" onchange="upload()" title="上传" /></span></div>function upload(){$.ajaxFileUpload ( { url:'<%=basePath%>sysperson/uploadpic', secureuri:false, fileElementId:'fileToUpload', dataType: 'text', success: function (data, status) {document.all.mypic.src="<%=basePath%>uploads/" + data;document.all.picpath.value = data;}, error : function(data, status, e) {alert(e);}});}

⑺ java 图片上传,图片上传是上传到哪里比较好服务器上还是数据库

图片上传一般会上传到你服务器那个项目里,到底上传到你服务器项目那个位置可以自己指定,数据库存路径就行了,用的时候直接读路径 。

⑻ 用Java写上传文件(图片)

首先希望我的回答能给你带来帮助首先写一个上传类public class procts_shang_chuang {public static boolean GOTO(String paht,FormFile file){boolean bool =false;int betered = 0;byte[] buufer = new byte [2042];if(file.getFileSize()>0&&file.getFileSize()<500000){try {InputStream in = file.getInputStream();//写入文件OutputStream out = new FileOutputStream(paht);while((betered=in.read(buufer, 0, 2042))!=-1){out.write(buufer, 0, betered);//将文件写入服务器}in.close();out.close();bool = true;} catch (FileNotFoundException e) {// TODO Auto-generated catch blockbool = false;e.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blockbool = false;e.printStackTrace();}} return bool;}public static boolean delete_file(String path){File file = new File(path);boolean bool = false;if(file.isFile()){System.out.println("文件存在"); bool = file.delete();}return bool;}}这个类主要是上传和删除图片的类那么下来直接调用就可以了 通过页面往action中提交数据 if(form instanceof Procts_addForm)//如果form是FilesForm{ String engding = request.getCharacterEncoding(); if((engding != null) && (engding.equalsIgnoreCase("utf-8"))){response.setContentType("text/html; charset=gb2312");//如果没有指定编码,编码格式为gb2312} FormFile file = procts_addForm.getFiles(); inpa = Huoqu_weiyi_biaoshi.getUniqueId(); String path = request.getRealPath("/guanliyuan/ji_zhu_procts_img/"+(inpa+file.getFileName())); System.out.println(path); String name = file.getFileName();inpa = "/guanliyuan/ji_zhu_procts_img/"+inpa+file.getFileName(); bool = procts_shang_chuang.GOTO(path, file); }这样就把图片上传上去了 仔细看看 批量上传和这个一样只是需要做一点点的改动而已有什么不明白的可以联系我Q号:549726411

⑼ java 中如何向服务器上传图片

我们使用一些已有的组件帮助我们实现这种上传功能。常用的上传组件:Apache 的 Commons FileUploadJavaZoom的UploadBeanjspSmartUpload以下,以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); }

⑽ 请问用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_size<file_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_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);//计算新图长宽 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图片文件上传|java怎样上传图片(写个例子谢谢);

赞 (0)