springMVC ajax 图片上传 一 前台
js
/*ajax 上传资源*/
function uploadResoures() {
var fileUpload=$("#file").val();
if($("#file").val() != "") {
$.ajaxFileUpload({
type: "POST",
url:"${pageContext.request.contextPath}/uploadResoures.do",
dataType: "json",
fileElementId:"file", // 文件的id
success: function(data){
if(data.filename!='') {
alert("保存路径:"+data.filename+"显示路径:"+data.filename2);
//图片显示
$("#resourcesPath").attr("value",data.filename);
$("#video-box video").prop("src",data.filename2);//source 里的 src 只会在渲染的时候被 check 一次.需要prop
// 自动播放
$(".videoClass")[0].play();
}
},
async:false,//同步
error: function () {
alert("上传失败");
},
});
} else {
alert("请先选择文件");
}
}
html
<div class="form-group" style="" id="video-box">
<input type="file" name="file" id="file" multiple class="file-loading" onchange="uploadResoures()" />
<video width="350" height="200" controls="controls" class="videoClass" style="">
<source src="/teacherOnline/fileStorage/031d14a5-0e07-41b0-8afb-b350a36bd93f.mp4" type="video/mp4" id="resourcesPathShow" name="resourcesPathShow">
</video>
</div>
二 后台
@RequestMapping(value="/uploadResoures.do")
@ResponseBody
public Map<String, Object> uploadResoures(HttpServletRequest req,ResouresUpload res,
@RequestParam(value = "file") MultipartFile file, Model model,
HttpServletRequest request){
Map<String, Object> map=new HashMap<String, Object>();
String fileName="";
String conetextPath=request.getSession().getServletContext().getContextPath();
if (!file.isEmpty()) {
fileName= file.getOriginalFilename();
String suffixName = fileName.substring(fileName.lastIndexOf("."));
String filePath = request.getSession().getServletContext().getRealPath("/fileStorage/");
fileName = UUID.randomUUID() + suffixName;
File dest = new File(filePath+fileName);
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
}
try {
file.transferTo(dest);
} catch (IOException e) {
e.printStackTrace();
}
}
String filename ="/fileStorage/" + fileName;
String filename2 =conetextPath+"/fileStorage/"+ fileName;
System.out.println("图片上传路径:"+filename2);
map.put("filename", filename);
map.put("filename2", filename2);
return map;
}
|