如何在spring mvc中上传图片并显示出来
(1)在spring mvc的配置文件中配置:
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="uploadTempDir" value="/tmp" /> <!-- 临时目录 -->
<property name="maxUploadSize" value="10485760"/> <!-- 10M -->
</bean>
(2)文件上传表单和结果展示页fileupload.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib prefix="mvc" uri="http://www.springframework.org/tags/form"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<title>Spring MVC文件上传</title>
</head>
<body>
<h2>图片文件上传</h2>
<mvc:form modelAttribute="user" action="upload.html"
enctype="multipart/form-data">
<table>
<tr>
<td>用户名:</td>
<td><mvc:input path="userName" /></td>
</tr>
<tr>
<td>选择头像:</td>
<td><input type="file" name="file" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Submit" /></td>
</tr>
</table>
</mvc:form>
<br><br>
<c:if test="${u !=null }">
<h2>上传结果</h2>
<table>
<c:if test="${u.userName != null }">
<tr>
<td>用户名:</td>
<td>${u.userName}</td>
</tr>
</c:if>
<c:if test="${u.logoSrc != null }">
<tr>
<td>头像:</td>
<td><img src="${u.logoSrc}" width="100px" height="100px"></td>
</tr>
</c:if>
</table>
</c:if>
</body>
</html>
(3)后台处理UploadController.java:
package cn.zifangsky.controller;
import java.io.File;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import cn.zifangsky.model.User;
import cn.zifangsky.utils.StringUtile;
@Controller
public class UploadController {
@RequestMapping(value = "/form")
public ModelAndView form() {
ModelAndView modelAndView = new ModelAndView("fileupload", "user", new User());
return modelAndView;
}
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public ModelAndView upload(User user, @RequestParam("file") MultipartFile tmpFile, HttpServletRequest request) {
ModelAndView modelAndView = new ModelAndView("fileupload");
if (tmpFile != null) {
// 获取物理路径
String targetDirectory = request.getSession().getServletContext().getRealPath("/uploads");
String tmpFileName = tmpFile.getOriginalFilename(); // 上传的文件名
int dot = tmpFileName.lastIndexOf('.');
String ext = ""; //文件后缀名
if ((dot > -1) && (dot < (tmpFileName.length() - 1))) {
ext = tmpFileName.substring(dot + 1);
}
// 其他文件格式不处理
if ("png".equalsIgnoreCase(ext) || "jpg".equalsIgnoreCase(ext) || "gif".equalsIgnoreCase(ext)) {
// 重命名上传的文件名
String targetFileName = StringUtile.renameFileName(tmpFileName);
// 保存的新文件
File target = new File(targetDirectory, targetFileName);
try {
// 保存文件
FileUtils.copyInputStreamToFile(tmpFile.getInputStream(), target);
} catch (IOException e) {
e.printStackTrace();
}
User u = new User();
u.setUserName(user.getUserName());
u.setLogoSrc(request.getContextPath() + "/uploads/" + targetFileName);
modelAndView.addObject("u", u);
}
return modelAndView;
}
return modelAndView;
}
}
在上面的upload方法中,为了接收上传的文件,因此使用了一个MultipartFile类型的变量来接收上传的临时文件,同时为了给文件进行重命名,我调用了一个renameFileName方法,这个方法的具体内容如下:
/**
* 文件重命名
*/
public static String renameFileName(String fileName) {
String formatDate = new SimpleDateFormat("yyMMddHHmmss").format(new Date()); // 当前时间字符串
int random = new Random().nextInt(10000);
String extension = fileName.substring(fileName.lastIndexOf(".")); // 文件后缀
return formatDate + random + extension;
}
注:上面用到的model——User.java:
package cn.zifangsky.model;
public class User {
private String userName; // 用户名
private String logoSrc; // 头像地址
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getLogoSrc() {
return logoSrc;
}
public void setLogoSrc(String logoSrc) {
this.logoSrc = logoSrc;
}
}
至此全部结束
效果如下:
(PS:纯手打,望采纳)
可以使用组件上传JspSmartUpload.这是一个类.
<form name="f1" id="f1" action="/demo/servlet/UploadServlet" method="post" enctype="multipart/form-data">
<table border="0">
<tr>
<td>用户名:</td>
<td><input type="text" name="username" id="username"></td>
</tr>
<tr>
<td>密码:</td>
<td><input type="password" name="password" id="password"></td>
</tr>
<tr>
<td>相片:</td>
<td><input type="file" name="pic" id="pic"></td>
</tr>
<tr>
<td>相片:</td>
<td><input type="file" name="pic2" id="pic2"></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit"></td>
</tr>
</table>
</form>
这里直接通过表单提交给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<files.getCount();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. <br>
*
* 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可以剪切以上的一部分.请自行调整.
实现上传图片功能在Springmvc中很好实现。下面将会展现完整例子。
开始需要在pom.xml加入几个jar,分别是:
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
接下来,在Springmvc的配置加入上传文件的配置(PS:我把springmvc的完整配置都展现出来):
<!--默认的mvc注解映射的支持 -->
<mvc:annotation-driven/>
<!-- 处理对静态资源的请求 -->
<mvc:resources location="/static/" mapping="/static/**" />
<!-- 扫描注解 -->
<context:component-scan base-package="com.ztz.springmvc.controller"/>
<!-- 视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<!-- 前缀 -->
<property name="prefix" value="/WEB-INF/jsp/"/>
<!-- 后缀 -->
<property name="suffix" value=".jsp"/>
</bean>
<!-- 上传文件 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8"/>
<!-- 最大内存大小 -->
<property name="maxInMemorySize" value="10240"/>
<!-- 最大文件大小,-1为不限制大小 -->
<property name="maxUploadSize" value="-1"/>
</bean>