接着昨天的来讲,昨天我们自制了一个简易的本地服务器。其中我的本地服务器tomcat端口号为88。今天我们来接着讲。
我这里用了ssm框架来做,首先你得搭建一个SpringMVC+Spring+mybatis的环境。如果你不会也没关系。可以看看我之前在最代码或者csdn上搭建的例子。
最代码例子的地址为:
http://www.zuidaima.com/share/2978816501746688.htm
csdn例子的地址为:
http://blog.csdn.net/u010798367/article/details/52995905
如果你不想学,那也没关系。其实上传的关键代码就一句:
public String uplodeFile(LearnFile lf,HttpServletRequest request) throws Exception{ long startTime = System.currentTimeMillis(); // 将当前上下文初始化给 CommonsMutipartResolver (多部分解析器) CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver( request.getSession().getServletContext()); // 检查form中是否有enctype="multipart/form-data" if (multipartResolver.isMultipart(request)) { // 将request变成多部分request MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request; // 获取multiRequest 中所有的文件名 Iterator iter = multiRequest.getFileNames(); while (iter.hasNext()) { // 一次遍历所有文件 MultipartFile file = multiRequest.getFile(iter.next().toString()); if (file != null) { String path = "D:/fdream/file/" + file.getOriginalFilename(); // 上传 file.transferTo(new File(path)); String fileurl="http://localhost:88/fdream/file"+file.getOriginalFilename(); LearnFile learnfile = new LearnFile(file.getOriginalFilename(), fileurl, lf.getUplodetime()); fileService.uplodeFile(learnfile); }else{ System.out.println("上传文件不能为空"); } } } long endTime = System.currentTimeMillis(); System.out.println("上传所花时间:" + String.valueOf(endTime - startTime) + "ms"); return "/index"; }
我也不知道这个公众号发文章怎么格式化。所以我简易你最好电脑访问。这样可以cp代码仔细看看!
我还是仔细来说明下,毕竟我会完整的实现一个项目,所以细节很重要。
-
首先,我在tomcat的server.xml配置文件配置两句话 。以后我就把上传的图片放到本地服务器D盘的fdream文件夹下面的img目录中,文件就放到D盘的fdream文件夹下面的file目录中。详情可以看下昨天的文章。
<Context docBase="D:\fdream\file" path="/fdream/file" debug="0" reloadable="true"/> <Context docBase="D:\fdream\img" path="/fdream/img" debug="0" reloadable="true"/>
2.现在来创建一张数据库表“learnfile”
CREATE TABLE `learnfile` ( `fileid` int(11) NOT NULL AUTO_INCREMENT COMMENT '文件id', `filename` varchar(255) DEFAULT NULL COMMENT '文件名', `fileurl` varchar(255) DEFAULT NULL COMMENT '文件上传地址', `uplodetime` varchar(255) DEFAULT NULL COMMENT '文件上传时间', PRIMARY KEY (`fileid`) ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
3.新建实体
package com.fdream.entity; /** * 文件实体 * @author quanmin * */ public class LearnFile { //文件id private int fileid; //文件名 private String filename; //文件上传地址 private String fileurl; //文件上传时间 private String uplodetime; public LearnFile() { } public LearnFile(int fileid, String filename, String fileurl, String uplodetime) { super(); this.fileid = fileid; this.filename = filename; this.fileurl = fileurl; this.uplodetime = uplodetime; } public LearnFile(String filename, String fileurl, String uplodetime) { this.filename = filename; this.fileurl = fileurl; this.uplodetime = uplodetime; } public int getFileid() { return fileid; } public void setFileid(int fileid) { this.fileid = fileid; } public String getFilename() { return filename; } public void setFilename(String filename) { this.filename = filename; } public String getFileurl() { return fileurl; } public void setFileurl(String fileurl) { this.fileurl = fileurl; } public String getUplodetime() { return uplodetime; } public void setUplodetime(String uplodetime) { this.uplodetime = uplodetime; } }
4.新建FileMapper
package com.fdream.mapper; import com.fdream.entity.LearnFile; /** * 文件持久层接口 * @author quanmin * */ public interface FileMapper { /** * 上传文件 * @param file * @return * @throws Exception */ public boolean uplodeFile(LearnFile lf) throws Exception; }
5.新建FileMapper.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.fdream.mapper.FileMapper"> <insert id="uplodeFile" parameterType="LearnFile"> insert into learnfile(filename,fileurl,uplodetime) values(#{filename},#{fileurl},#{uplodetime}) </insert> </mapper>
6.新建IFileService
package com.fdream.service; import com.fdream.entity.LearnFile; /** * 文件服务层接口 * @author quanmin * */ public interface IFileService { /** * 上传文件 * @param file * @return * @throws Exception */ public boolean uplodeFile(LearnFile lf) throws Exception; }
7.新建FileServiceImpl
package com.fdream.service.impl; import javax.annotation.Resource; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.fdream.entity.LearnFile; import com.fdream.mapper.FileMapper; import com.fdream.service.IFileService; /** * 文件服务层接口实现 * @author quanmin * */ @Service @Transactional //此处不再进行创建SqlSession和提交事务,都已交由spring去管理了。 public class FileServiceImpl implements IFileService { @Resource private FileMapper fileDao; @Override public boolean uplodeFile(LearnFile lf) throws Exception { return fileDao.uplodeFile(lf); } }
8.新建FileController
package com.fdream.controller; import java.io.File; import java.util.Iterator; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import org.springframework.web.multipart.commons.CommonsMultipartResolver; import com.fdream.entity.LearnFile; import com.fdream.service.IFileService; /** * * 文件控制层 * @author quanmin * */ @Controller @RequestMapping("/file") public class FileController { @Autowired private IFileService fileService; /** * 上传文件 * @param lf * @param request * @return * @throws Exception */ @RequestMapping("/uplodeFile") public String uplodeFile(LearnFile lf,HttpServletRequest request) throws Exception{ long startTime = System.currentTimeMillis(); // 将当前上下文初始化给 CommonsMutipartResolver (多部分解析器) CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver( request.getSession().getServletContext()); // 检查form中是否有enctype="multipart/form-data" if (multipartResolver.isMultipart(request)) { // 将request变成多部分request MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request; // 获取multiRequest 中所有的文件名 Iterator iter = multiRequest.getFileNames(); while (iter.hasNext()) { // 一次遍历所有文件 MultipartFile file = multiRequest.getFile(iter.next().toString()); if (file != null) { String path = "D:/fdream/file/" + file.getOriginalFilename(); // 上传 file.transferTo(new File(path)); String fileurl="http://localhost:88/fdream/file"+file.getOriginalFilename(); LearnFile learnfile = new LearnFile(file.getOriginalFilename(), fileurl, lf.getUplodetime()); fileService.uplodeFile(learnfile); }else{ System.out.println("上传文件不能为空"); } } } long endTime = System.currentTimeMillis(); System.out.println("上传所花时间:" + String.valueOf(endTime - startTime) + "ms"); return "/index"; } }
9.这些我就不一一说明了,如果不懂ssm框架的可以先参照那两篇文章。接下来后台代码已经实现了,我写一个jsp页面addFile.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!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> <script type="text/javascript" src="js/getnowDate.js"></script> <base href="<%=basePath%>"/> </head> <body onload="a();"> <form action="<%=basePath%>file/uplodeFile" method="post" enctype="multipart/form-data"> 文件:<input type="file" name="file"/> <input name="uplodetime" type="hidden" id="nowDate"/> <input type="submit" value="上传"/> </form> </body> </html>
记住,一定不要忘了加enctype="multipart/form-data"
然后开始访问页面。
添加成功后跳转到index页面
现在我们来看看数据库。
再来看看d盘的fdream文件夹下的file目录
好的,这个已经成功完成。接下来就是实践一个项目了。也是基于这上面做的。所以大家可以仔细看看最代码和csdn的框架教学。