pom文件导入上传文件jar包
<!--上传文件-->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
html代码
<input type="file" id="inputFile" style="display: none;"/>
<div style="width: 300px; height: 200px;" onclick="$('#inputFile').click()">
<p>请选择图片:</p>
<img src="" id="showImg"
style="width: 300px; height: 200px; display: none; position: absolute; top: 0; left: 0;"/>
</div>
js文件显示缩略图
$(function(){
$("#inputFile").on("change",function(){
var file=this.files[0];
if(this.files && file){
var reader=new FileReader();
reader.onload=function(e){
$("#showImg").attr("src",e.target.result);
}
reader.readAsDataURL(file);
}
});
});
ajax上传文件
var empName = $.trim(consoleDlg.find("#empName").val());
var formData = new FormData(); //不能传的参数太多,好像有限制,一般传文件和描述即可
formData.append("photo", document.getElementById("inputFile").files[0]);
formData.append("empName",empName);
console.log(formData)
$.ajax({
url : "/add",
type : 'POST',
cache : false,
data : formData,
dataType : 'json',
contentType: false,
processData: false,
async : true,
success : function(response) {
},
error : function(textStatus, e) {
alert("系统ajax交互错误: " + textStatus);
}
});
springmvc配置上传文件的大小限制等
<!-- 上传文件 -->
<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>
controller类接收及图片保存(测试没有使用service层)
@RequestMapping(value={"/add"})
@ResponseBody
public Msg add(@RequestParam("photo") MultipartFile[] files,@RequestParam("empName") String empName) {
String filename = files[0].getOriginalFilename();// 文件名
String[] strArray = filename.split("\\.");
int suffixIndex = strArray.length -1;
// File file = new File(System.getProperty("evan.webapp")+"/upload/"+UUID.randomUUID().toString().substring(10)+"."+strArray[suffixIndex]);
File file = new File("D:"+"/upload/"+UUID.randomUUID().toString().substring(10)+"."+strArray[suffixIndex]);
try {
FileUtils.copyInputStreamToFile(files[0].getInputStream(), file);
} catch (IOException e) {
e.printStackTrace();
}
return Msg.success();
}