Maven+SpringMVC实现文件上传

效果演示

毕业设计中有一模块是实现文件上传的。由于初学SpringMVC不咋了解这该如何操作,故现在把操作过程记录了下来

实现步骤

第一步 首先要先设计传输页面中的form表单,要设计其格式为enctype=“multipart/form-data”

<form  method="post" enctype="multipart/form-data" action="#">
	<input type="file" name="files" id="file" onchange="verificationPicFile(this)">仅允许.jpg或.png图片的上传
</form>

这里我上传的是图片信息,所以对图片格式进行了一下简单的筛选

<script>
		//图片类型验证
		function verificationPicFile(file) {
		var fileTypes = [ ".jpg", ".png"];
		var filePath = file.value;
		//当括号里面的值为0、空字符、false 、null 、undefined的时候就相当于false
		if (filePath) {
			var isNext = false;
			var fileEnd = filePath.substring(filePath.indexOf("."));
					for (var i = 0; i < fileTypes.length; i++) {
						if (fileTypes[i] == fileEnd) {
								isNext = true;
									break;
							}
						}
						if (!isNext) {
							alert('不接受此文件类型');
								file.value = "";
									return false;
							}
						} else {
							return false;
						}
			}
</script>

之后要在Maven中加载对应额jar包
pom.xml

<!-- photo上传 -->
		<dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.3</version>
        </dependency>

其次要对SpringMVC的配置文件进行添加
spring-mvc.xml

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 如果上传后出现文件名中文乱码可以使用该属性解决 -->
        <property name="defaultEncoding" value="UTF-8"/>
        <!-- 单位是字节,不设置默认不限制总的上传文件大小,这里设置总的上传文件大小不超过10M(10*1024*1024-->
        <property name="maxUploadSize" value="10485760"/>
        <!-- 跟maxUploadSize差不多,不过maxUploadSizePerFile是限制每个上传文件的大小,而maxUploadSize是限制总的上传文件大小 -->
        <property name="maxUploadSizePerFile" value="10485760"/>
    </bean>

编写UploadUtils工具类
UploadUtils.java


import java.io.File;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

public class UploadUtils {
	public boolean upload(String path, @RequestParam("file") MultipartFile file) throws Exception {
        //如果文件不为空,写入上传路径
		try {
			if (!file.isEmpty()) {
	            //上传文件名
	            String filename = file.getOriginalFilename();
	            File filepath = new File(path, filename);
	            //判断路径是否存在,如果不存在就创建一个
	            if (!filepath.getParentFile().exists()) {
	                filepath.getParentFile().mkdirs();
	            }
	            System.out.println("图片保存路径:"+path);
	            //将上传文件保存到一个目标文件当中
	            file.transferTo(new File(path + File.separator + filename));
	            return true;
	        } else {
	            return false;
	        }
		} catch (Exception e) {
			// TODO: handle exception
		}
		return false;
    }
}

最后在SpringMVC的@Controller中添加上传代码

import java.io.UnsupportedEncodingException;
import java.sql.Date;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
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.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.zhenzi.sms.ZhenziSmsClient;
@Controller
@RequestMapping("/Doctor")
public class DoctorController {
@RequestMapping(value = "addarticle")
	public ModelAndView addarticle(@RequestParam("files") MultipartFile files,HttpServletRequest request) {
			try {
	            String path = request.getServletContext().getRealPath("resources/photo");
				up.upload(path, files);
			} catch (Exception e) {
				e.printStackTrace();
			}
			return new ModelAndView("视图");
	}
}

ps:这里上传的图片或者文档在重启服务器后会消失,我也不知道为何,还请大佬赐教。

未经授权,禁止转载

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值