SpringMVC ajax技术无刷新文件上传下载删除示例

参考

Spring MVC中上传文件实例

SpringMVC结合ajaxfileupload.js实现ajax无刷新文件上传

Spring MVC 文件上传下载 (FileOperateUtil.java 压缩,重命名工具类)

controller代码

@Controller
@RequestMapping(value = "/file")
public class FileController extends BaseController {
/**
* 上传文件
*
* @return JSON
* @throws Exception
*/
@ResponseBody
@RequestMapping(value = "/upload")
public Message upload(HttpServletRequest request,
HttpServletResponse response) throws Exception {
logBefore(logger, "上传文件"); Message message = new Message();
PageData pd = new PageData();
pd = this.getPageData(); // 这里实现文件上传操作用的是commons.io.FileUtils类,它会自动判断/upload是否存在,不存在会自动创建
String realPath = request.getSession().getServletContext() .getRealPath("/upload/file");
logBefore(logger, "realPath: " + realPath); // 上传文件的原名(即上传前的文件名字)
String originalFilename = null;
// 如果只是上传一个文件,则只需要MultipartFile类型接收文件即可,而且无需显式指定@RequestParam注解
// 如果想上传多个文件,那么这里就要用MultipartFile[]类型来接收文件,并且要指定@RequestParam注解
// 上传多个文件时,前台表单中的所有<input
// type="file"/>的name都应该是file,否则参数里的file无法获取到所有上传的文件
MultipartFile file = FileUpload.getMultipartFileByName(request, "file");
if (file.isEmpty()) {
message.response = ResponseStatus.FAILED.getStatus();
message.message = "请选择文件后上传!";
} else {
originalFilename = file.getOriginalFilename();
logBefore(logger, "文件原名: " + originalFilename);
logBefore(logger, "文件名称: " + file.getName());
logBefore(logger, "文件长度: " + file.getSize());
logBefore(logger, "文件类型: " + file.getContentType());
logBefore(logger, "========================================");
try {
// 这里不必处理IO流关闭的问题,因为FileUtils.copyInputStreamToFile()方法内部会自动把用到的IO流关掉
// 此处也可以使用Spring提供的MultipartFile.transferTo(File dest)方法实现文件的上传
FileUtils.copyInputStreamToFile(file.getInputStream(), new File(realPath, originalFilename));
} catch (IOException e) {
logBefore(logger, "文件[" + originalFilename + "]上传失败,堆栈轨迹如下");
e.printStackTrace();
message.response = ResponseStatus.FAILED.getStatus();
message.message = "出错,服务器繁忙,请稍后再试。";
} }
//System.out.println(request.getContextPath() + "/upload/" + originalFilename);
message.response = ResponseStatus.SUCCESS.getStatus();
message.message = "上传成功!"; return message;
} /**
* 单条记录删除
*
* @return JSON
* @throws Exception
*/
@ResponseBody
@RequestMapping(value = "/delete")
public Message delete() {
logBefore(logger, "删除文件");
PageData pd = new PageData();
Message message = new Message();
String file_id = (String) pd.get("file_id");
// 获取对应文件名和地址
String filePath = "";
//TODO:删除本地文件,删除数据库记录
try {
pd = this.getPageData();
AccidentService.delete(pd);
message.response = ResponseStatus.SUCCESS.getStatus();
message.message = "删除成功";
} catch (Exception e) {
logger.error(e.toString(), e);
message.response = ResponseStatus.FAILED.getStatus();
message.message = "出错,服务器繁忙,请稍后再试。";
}
return message;
} /**
* 获取数据列表页
*
* @param page
* 页面请求对象
* @return 跳转页面
*/
@RequestMapping(value = "/list")
public ModelAndView list(HttpServletRequest request, Page page) {
logBefore(logger, "列表File");
// if(!Jurisdiction.buttonJurisdiction(menuUrl, "cha")){return null;}
// //校验权限
ModelAndView mv = this.getModelAndView();
PageData pd = new PageData();
//文件储存地址
//String realPath = request.getSession().getServletContext() .getRealPath("/upload/file");
//TODO:获取数据库文件信息
try {
pd = this.getPageData();
mv.setViewName("security/files/file_list");
mv.addObject(Const.SESSION_QX, this.getHC()); // 按钮权限
} catch (Exception e) {
logger.error(e.toString(), e);
}
return mv;
} /**
* 下载文件
*
* @param page
* 页面请求对象
* @return 跳转页面
* @throws IOException
*/
@RequestMapping(value = "/download")
public ResponseEntity<byte[]> download(HttpServletRequest request,
HttpServletResponse response, Page page) throws IOException {
logBefore(logger, "下载File");
PageData pd = new PageData();
String file_id = (String) pd.get("file_id");
// 获取对应文件名和地址
String fileName = "1.1.1关于印发《交运集团2016年安全生产工作意见》的通知.doc";
// fileName = "222";
String filePath = request.getServletContext().getRealPath(
"/upload/file")
+ "\\1.doc";
logBefore(logger, "fileName: " + fileName);
logBefore(logger, "filePath: " + filePath);
File file = new File(filePath);
try {
fileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");// 为了解决中文名称乱码问题
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} // 下载文件
HttpHeaders headers = new HttpHeaders();
headers.setContentDispositionFormData("attachment", fileName);
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); try {
return new ResponseEntity<byte[]>(
FileUtils.readFileToByteArray(file), headers,
HttpStatus.CREATED);
} catch (IOException e) {
e.printStackTrace();
return null;
}
} }

其中一个FileUpload类的代码

package com.jiaoyun.util;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List; import javax.servlet.http.HttpServletRequest; import org.apache.commons.io.FileUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver; /**
* 上传文件 创建人:James 创建时间:2014年12月23日
*
* @version
*/
public class FileUpload { /**
* @param file
* //文件对象
* @param filePath
* //上传路径
* @param fileName
* //文件名
* @return 文件名
*/
public static String fileUp(MultipartFile file, String filePath, String fileName) {
String extName = ""; // 扩展名格式:
try {
if (file.getOriginalFilename().lastIndexOf(".") >= 0) {
extName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
}
copyFile(file.getInputStream(), filePath, fileName + extName).replaceAll("-", "");
} catch (IOException e) {
System.out.println(e);
}
return fileName + extName;
} /**
* 写文件到当前目录的upload目录中
*
* @param in
* @param fileName
* @throws IOException
*/
private static String copyFile(InputStream in, String dir, String realName) throws IOException {
File file = new File(dir, realName);
if (!file.exists()) {
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
file.createNewFile();
}
System.out.println(file.getAbsolutePath());
FileUtils.copyInputStreamToFile(in, file);
return realName;
} /**
* @param request
* //requst请求
* @param filePath
* //上传路径
* @param fileName
* //文件名
* @return 文件名
* @throws IOException
* @throws IllegalStateException
*/
public static String upload(HttpServletRequest request, String filePath, String fileName)
throws IllegalStateException, IOException {
String extName = ""; // 扩展名格式:
String path = "";
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
request.getSession().getServletContext());
// 判断 request 是否有文件上传,即多部分请求
if (multipartResolver.isMultipart(request)) {
// 转换成多部分request
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
// 取得request中的所有文件名
Iterator<String> iter = multiRequest.getFileNames();
while (iter.hasNext()) {
// 取得上传文件
MultipartFile file = multiRequest.getFile(iter.next());
if (file != null) {
// 取得当前上传文件的文件名称
String myFileName = file.getOriginalFilename();
// 如果名称不为“”,说明该文件存在,否则说明该文件不存在
if (myFileName.trim() != "") {
// 重命名上传后的文件名
if (file.getOriginalFilename().lastIndexOf(".") >= 0) {
extName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
}
// 定义上传路径
path = filePath + "/" + fileName + extName;
// System.out.println("---------------------");
// System.out.println(path);
// System.out.println("---------------------");
File localFile = new File(path);
file.transferTo(localFile);
}
}
} }
return extName;
} /**
* @param request
* //requst请求
* @param filePath
* //上传路径
* @param fileName
* //文件名
* @return 文件名
* @throws IOException
* @throws IllegalStateException
*/
public static String[] uploadMultiple(HttpServletRequest request, String filePath, String[] fileName)
throws IllegalStateException, IOException {
String[] extName = new String[fileName.length]; // 扩展名格式:
String path = "";
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
request.getSession().getServletContext());
// 判断 request 是否有文件上传,即多部分请求
if (multipartResolver.isMultipart(request)) {
// 转换成多部分request
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
// 取得request中的所有文件名
Iterator<String> iter = multiRequest.getFileNames();
int i = 0;
while (iter.hasNext()) {
// 取得上传文件
MultipartFile file = multiRequest.getFile(iter.next());
if (file != null) {
// 取得当前上传文件的文件名称
String myFileName = file.getOriginalFilename();
// 如果名称不为“”,说明该文件存在,否则说明该文件不存在
if (myFileName.trim() != "") {
// 重命名上传后的文件名
if (file.getOriginalFilename().lastIndexOf(".") >= 0) {
extName[i] = file.getOriginalFilename()
.substring(file.getOriginalFilename().lastIndexOf("."));
}
// 定义上传路径
fileName[i] = fileName[i].replace(extName[i], "");
path = filePath + "/" + fileName[i] + extName[i];
// path = fileName[i] + extName[i];
File localFile = new File(path);
file.transferTo(localFile);
System.out.println(localFile.getAbsolutePath());
}
}
i++;
} }
return extName;
} /**
* 从request那里得到所有MultipartFile
*/
public static List<MultipartFile> getMultipartFileFromRequest(HttpServletRequest request)
throws IllegalStateException, IOException { List<MultipartFile> fileList = new ArrayList<MultipartFile>();
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
request.getSession().getServletContext());
// 判断 request 是否有文件上传,即多部分请求
if (multipartResolver.isMultipart(request)) {
// 转换成多部分request
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
// 取得request中的所有文件名
Iterator<String> iter = multiRequest.getFileNames();
while (iter.hasNext()) {
MultipartFile file = multiRequest.getFile(iter.next());
System.out.println(file.getName()+"11111111111");
if (file != null && file.getSize() > 0) {
fileList.add(file);
}
}
}
return fileList;
}
/**
* @Description:删除文件
*/
public static void deleteFile(String bucketName, String key) {
return;
}
public static void deleteFile(String bucketName) {
return;
} /**
* 从request那里得到所有MultipartFile
*/
public static MultipartFile getMultipartFileByName(HttpServletRequest request,String name)
throws Exception {
MultipartFile file=null;
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
request.getSession().getServletContext());
// 判断 request 是否有文件上传,即多部分请求
if (multipartResolver.isMultipart(request)) {
// 转换成多部分request
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
// 取得request中的所有文件名
Iterator<String> iter = multiRequest.getFileNames();
while (iter.hasNext()) {
file = multiRequest.getFile(iter.next());
if (file != null&&file.getName().equals(name)) {
return file;
}
}
}
return file;
} /**
* 根据文件得到后缀名
* @param file
* @return
*/
public static String getExtNameByString(String file){
String extName="";
if (file.lastIndexOf(".") >= 0){
extName = file.substring(file.lastIndexOf("."));
}
return extName;
} public static String getExtName(MultipartFile file){
String extName="";
if (file.getOriginalFilename().lastIndexOf(".") >= 0){
extName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
}
return extName;
} }

html前台页面代码

上传按钮

<a class="btn red btn-circle btn-sm"
href="javascript:importData('file/upload');"> 上传文件 <i
class="fa fa-upload"></i>
</a>
<script>
function importData(url) {
dialog = bootbox.confirm({
title : '请选择文件',
message : '<form id="uploadFileForm" class="form-horizontal"><input type="file" name="file" value="选择文件" id="uploadFileInput" class="btn sbold green"/></form>',
buttons: {
confirm: {
label: '上传',
className: 'btn-success'
},
cancel: {
label: '取消',
className: 'btn-danger'
}
},
callback: function (result) {
if(result){
var formData = new FormData($( "#uploadFileForm" )[0]);
$.ajax({
type: "POST",
url: url,
data: formData,
dataType:'json',
async: false,
cache: false,
contentType: false, //必须false才会自动加上正确的Content-Type
processData: false, //必须false才会避开jQuery对 formdata 的默认处理
error: function(request) {
bootbox.alert("网络异常");
},
success: function(data){
   if (data.response == 'true') {
   bootbox.alert("上传成功!");
$table.bootstrapTable('refresh');
dialog.modal('hide');
    } else {
     bootbox.alert(data.message);
    }
}
});
}
}
});
}
</script>

下载按钮

<a class="btn default" id="demo_1"
href="file/download?file_id=1" target="_blank"> 下载文件 <i
class="fa fa-download"></i>
</a>

删除按钮

<a class="btn red" id="demo_1" href="file/delete?file_id=1"> 删除文件 <i class="fa fa-remove"></i>
</a>
上一篇:OpenCV 编程简单介绍(矩阵/图像/视频的基本读写操作)


下一篇:ie8实现无刷新文件上传