1.jsp文件
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<c:set var="basePath" value="${pageContext.request.contextPath}"/>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="pragma" content="no-cache"/>
<meta http-equiv="cache-control" content="no-cache"/>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title> test file upload </title>
</head>
<body>
<form action="/InstaiElective/course/uploadCourseCover" method="post" enctype="multipart/form-data" >
parameter1: <input type="text" name="parameter1"><br><br>
parameter1: <input type="text" name="parameter1"><br><br>
<input type="file" name="file"><br><br>
<input type="submit" name="submit" value="submit">
</form>
</body>
</html>
2.controller文件:
@RequestMapping(value = "/uploadCourseCover", method = RequestMethod.POST)
public @ResponseBody ReturnData<String> uploadCourseCover(@RequestParam("file") MultipartFile file, HttpServletRequest request ) throws CustomException {
ReturnData<String> rd = new ReturnData<String>();
String parameter1 = request.getParameter("parameter1");
String parameter2 = request.getParameter("parameter2");
String picUrl = courseRepositoryService.upload(file,request);
rd.setCode(Conss.RETURNDATA_SUCCEEDED);
rd.setDesc("upload success");
rd.setData(picUrl);
return rd;
}
3.service文件:
public String upload(MultipartFile file, HttpServletRequest request) {
String absolutePath = null;
if (!file.isEmpty()) {
ServletContext sc = request.getSession().getServletContext();
// 设定文件保存的目录
String dir = sc.getRealPath("/img");
// 得到上传时的文件名
String fileName = file.getOriginalFilename();
String strs[] = fileName.split("\\.");
fileName = "";
for(int i=0;i<strs.length-1;i++){
fileName += strs[i];
}
//避免文件名重复 --重命名文件
fileName = String.valueOf(System.currentTimeMillis()) + "." + strs[strs.length-1];
try {
FileUtils.writeByteArrayToFile(new File(dir, fileName), file.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
absolutePath = "/img/" + fileName;
}
return absolutePath;
}
4.文件下载:
http://www.cnblogs.com/ungshow/archive/2009/01/12/1374491.html
http://www.2cto.com/kf/201409/331289.html
网友评论