如何在spring mvc中上传图片并显示出来

如何在spring mvc中上传图片并显示出来

可以使用组件上传JspSmartUpload.这是一个类.
f1" id=" f1" > 用户名: 密码: 相片: 相片: 这里直接通过表单提交给servlet访问,spring中的话需要配置(一般就不用servlet了,自行配置). 以上在JSp页面中,以下是servlet/action中的代码,由于采用了 spring框架,怎么做你知道的(没有servlet但是有action). package com.demo.servlet; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Random; import java.util.UUID; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.jspsmart.upload.File; import com.jspsmart.upload.Files; import com.jspsmart.upload.Request; import com.jspsmart.upload.SmartUpload; public class UploadServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { SmartUpload su = new SmartUpload(); //初始化 su.initialize(this.getServletConfig(), request, response); try { //限制格式 //只允许哪几种格式 su.setAllowedFilesList("jpg,JPG,png,PNG,bmp,gif,GIF"); //不允许哪几种格式上传,不允许exe,bat及无扩展名的文件类型 //su.setDeniedFilesList("exe,bat,,"); //限制大小,每个上传的文件大小都不能大于100K su.setMaxFileSize(100*1024); //上传文件的总大小不能超过100K //su.setTotalMaxFileSize(100*1024); //上传 su.upload(); //唯一文件名 //得到文件集合 Files files = su.getFiles(); for(int i=0;i { //获得每一个上传文件 File file = files.getFile(i); //判断客户是否选择了文件 if(file.isMissing()) { continue; } //唯一名字 Random rand = new Random(); //String fileName = System.currentTimeMillis()+""+rand.nextInt(100000)+"."+file.getFileExt(); String fileName = UUID.randomUUID()+"."+file.getFileExt(); //以当前日期作为文件夹 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); String dirPath = sdf.format(new Date()); //获得物理路径 String realDirPath= this.getServletContext().getRealPath(dirPath); java.io.File dirFile = new java.io.File(realDirPath); //判断是否存在 if(!dirFile.exists()) { //创建文件夹 dirFile.mkdir(); } //保存 file.saveAs("/"+dirPath+"/"+fileName); //file.saveAs("/uploadFiles/"+fileName); } //原名保存 //su.save("/uploadFiles"); } catch (Exception e) { System.out.println("格式错误"); } //获得用户名 Request req = su.getRequest(); String username = req.getParameter("username"); System.out.println(username); } /** * The doPost method of the servlet. * * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } } 特别注意导的包是JspSmartUpload中的还是java.io.*中的. 再次说明,这段代码是servlet中的,spring中的action可以剪切以上的一部分.请自行调整.








猜你喜欢

转载自blog.csdn.net/Helloworld_jin/article/details/47264985
今日推荐