一、简介
通过把文件上传到tomcat的虚拟目录,实现代码和资源文件分开。
二、环境
spring+springmvc+mybatis
三、代码实现
1.导入文件上传的jar
<!--上传图片-->
<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
2.在springmvc.xml中配置multipart类型解析器
<!--文件上传配置-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 请求的编码格式,必须和jSP的pageEncoding属性一致,以便正确读取表单的内容,默认为ISO-8859-1 -->
<property name="defaultEncoding" value="utf-8"/>
<!-- 上传文件大小上限,单位为字节(10485760=10M) -->
<property name="maxUploadSize" value="10485760"/>
<property name="maxInMemorySize" value="40960"/>
</bean>
3.springmvc文件上传
package com.test.demo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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.commons.CommonsMultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
@Controller
public class UploadController {
/**
* 图片上传接口
* @param model
* @return
*/
@RequestMapping(value = "/uploads",method = {RequestMethod.POST})
@ResponseBody
public String fileUploads(@RequestParam("file") CommonsMultipartFile file , HttpServletRequest request, Model model) throws IOException {
//获取文件名 : file.getOriginalFilename();
String uploadFileName = file.getOriginalFilename();
String data=null;
//如果文件名为空,直接回到首页!
if ("".equals(uploadFileName)){
data="";
//封装数据
return data;
}
System.out.println("上传文件名 : "+uploadFileName);
//上传路径保存设置
String path = request.getServletContext().getRealPath("/upload");
//如果路径不存在,创建一个
File realPath = new File(path);
if (!realPath.exists()){
realPath.mkdir();
}
System.out.println("上传文件保存地址:"+realPath);
InputStream is = file.getInputStream(); //文件输入流
OutputStream os = new FileOutputStream(new File(realPath,uploadFileName)); //文件输出流
//读取写出
int len=0;
byte[] buffer = new byte[1024];
while ((len=is.read(buffer))!=-1){
os.write(buffer,0,len);
os.flush();
}
os.close();
is.close();
System.out.println(realPath+"/"+uploadFileName);
//返回给前端图片名
data=uploadFileName;
//封装数据
return data;
}
}
4.前端使用ajax
<p>文件上传</p>
<div class="san3">
<input type="file" name="fujianID" id="fujianID" onchange="UpdateFile()"/>
<input type = "hidden" name="fujianid" id="file2" />
</div>
<script>
//上传文件
function UpdateFile(){
var file_fujian = $("input[name='fujianID']").val();//用户文件内容(文件)
// 判断文件是否为空
if ( file_fujian== "") {
layer.msg("青选择上传的附件",{icon:1,time:1000});
return false;
}
//判断文件类型,根据自己需要来做判断
/*var fujianID = file_fujian.substring( file_fujian.lastIndexOf(".") + 1).toLowerCase();
if(fujianID != "xls" && fujianID !="xlsx"&&fujianID !="docx"&&fujianID !="doc"&&fujianID !="txt"){
layer.msg("请选择Execl文或者word文件或者txt文件格式!",{icon:1,time:2000});
return false;
}*/
//判断文件大小
var size1 = $("input[name='fujianID']")[0].files[0].size;
if (size1>104857600) {
layer.msg("上传的附件不能大于100M",{icon:1,time:2000});
return false;
}
boo1 = true;
var type = "file";
var formData = new FormData();//这里需要实例化一个FormData来进行文件上传
formData.append(type,$("#fujianID")[0].files[0]);
$.ajax({
type:'POST',
url:"uploads",
data:formData,
async:false,
processData:false,
contentType:false,
success:function(res){
console.log(res)
}
});
}
</script>
如果想要显示你的上传成功的图片需要配置tomcat的·虚拟目录映射
找到这个目录点击OK
最后别忘了设置路径