利用SpringMVC和Ajax实现文件上传功能
程序员文章站
2023-11-27 14:17:16
个人根据相关资料实现利用springmvc和ajax实现文件上传功能:
环境:
1.jdk1.7
2.maven3.3.9
3.tomcat7
第一步:
导入相...
个人根据相关资料实现利用springmvc和ajax实现文件上传功能:
环境:
1.jdk1.7
2.maven3.3.9
3.tomcat7
第一步:
导入相关jar包:
第二步:
配置springmvc-config.xml
<?xml version="1.0" encoding="utf-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xsi:schemalocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <context:component-scan base-package="com.lc" /> <!-- 配置视图解析器 --> <bean id="viewresolver" class="org.springframework.web.servlet.view.internalresourceviewresolver"> <property name="prefix" value="/web-inf/page/"></property> <property name="suffix" value=".jsp"></property> </bean> <bean id="multipartresolver" class="org.springframework.web.multipart.commons.commonsmultipartresolver"> <!--上传文件的最大大小 --> <property name="maxuploadsize" value="17367648787"></property> <!-- 上传文件的编码 --> <property name="defaultencoding" value="utf-8"></property> </bean> </beans>
第三步:
配置web.xml
<?xml version="1.0" encoding="utf-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemalocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="webapp_id" version="3.1"> <display-name>fileupload</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <!--springmvc的控制分发器 --> <servlet> <servlet-name>springdispatcherservlet</servlet-name> <servlet-class>org.springframework.web.servlet.dispatcherservlet</servlet-class> <init-param> <param-name>contextconfiglocation</param-name> <param-value>classpath:springmvc-config.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springdispatcherservlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
第四步:
新建一个controller类,并实现文件上传的功能
import java.io.file; import java.util.hashmap; import java.util.map; import java.util.random; import javax.json.json; import javax.servlet.http.httpservletrequest; 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.bind.annotation.responsebody; import org.springframework.web.multipart.multipartfile; import com.alibaba.fastjson.json; import com.fasterxml.jackson.databind.util.jsonpobject; @controller public class fileuploadcontroller { @requestmapping(value = "index", method = requestmethod.get) public string index() { return "index"; } @requestmapping(value = "/upload", method = requestmethod.post) @responsebody public string upload(@requestparam("file") multipartfile file, httpservletrequest request) { map<string, string> modelmap = new hashmap<>(); if (!file.isempty()) { string storepath = "e://images"; random r = new random(); string filename = file.getoriginalfilename(); string[] split = filename.split(".jpg"); filename = split[0] + r.nextint(1000); filename = filename + ".jpg"; file filepath = new file(storepath, filename); if (!filepath.getparentfile().exists()) { filepath.getparentfile().mkdirs();// 如果目录不存在,则创建目录 } try { file.transferto(new file(storepath + file.separator + filename));// 把文件写入目标文件地址 } catch (exception e) { e.printstacktrace(); modelmap.put("back", "error"); string json = json.tojsonstring(modelmap); return json; } modelmap.put("back", "success"); } else { modelmap.put("back", "error"); } string json = json.tojsonstring(modelmap); return json; } }
第五步:
在web-inf下,新建一个pages文件夹,并创建实现文件上传的jsp或者html文件(我使用的是jsp):
在index.jsp下写入相关的ajax的方法,在使用ajax之前必须先导入js库。
<body> <form id="uploadform" enctype="multipart/form-data" method="post"> <input type="file" name="file"> </form> <br> <input type="button" id="upload" value="上传"> </body> <script src="https://cdn.bootcss.com/jquery/1.10.2/jquery.min.js"></script> <script type="text/javascript"> $(function() { $('#upload').click(function() { var formdata = new formdata($('#uploadform')[0]); $.ajax({ type : 'post', url : 'upload', data : formdata, cache : false, processdata : false, contenttype : false, }).success(function(data) { var result = json.parse(data); alert(result.back); }).error(function() { alert("上传失败"); }); }); }); </script>
第六步:
进行测试
上传文件
上传成功
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。