jquery.ocupload上传文件到指定目录

时间:2022-07-06 01:32:27

首先引入两个js

 <script type="text/javascript" src="${pageContext.request.contextPath }/resource/js/jquery-1.8.3.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath }/resource/js/jquery_ocupload.js"></script>
 <body>
<button type="button" id="import">上传文件</button>
</body>
 <script type="text/javascript">
$("#import").upload({
name : 'upload', // 文件名,要与ation中的参数名一致
action : '${pageContext.request.contextPath}/upload/file.do', // action路径
enctye : 'multipart/form-data', // 设置编码格式,默认multipart/form-data
autoSubmit : true, // 选中文件提交表单
onComplete : function(flag) { // 请求完成后的回调函数
if (flag == '0') {
alert("数据导入成功!");
} else {
alert("数据导入失败!");
}
}
});
</script>

后台代码:

     @RequestMapping(method=RequestMethod.POST, value="/upload/file")
@ResponseBody
private String upload(MultipartFile upload, HttpServletRequest request) throws IOException {
String flag = "";
String path = request.getRealPath("/") + "../dexing/politik"; // 存放文件的路径
File file = new File(path, upload.getOriginalFilename());
if (file.exists()) { // 判断文件是否已经存在
flag = "1";
return flag;
} else {
try {
upload.transferTo(file); // 将文件写到指定路径下
} catch (Exception e) {
flag = "-1";
e.printStackTrace();
return flag;
}
}
flag = "0";
return flag;
}