springmvc文件上传
control层
@ResponseBody
@RequestMapping(value = "/addKnowledgeFile")
public ModelAndView addKnowledgeFile(@RequestParam(value = "file", required = false) MultipartFile file,
HttpServletRequest request,HttpServletResponse response,String knowledgeId, String categoryId, String details) {
XSmKnowledge knowledge = new XSmKnowledge();
boolean isMulitpart = ServletFileUpload.isMultipartContent(request);
if (isMulitpart) {
try {
String originalFileName = file.getOriginalFilename(); // 原始的文件名
//通过ftp上传文件/ 1.img 2.video 3.other分类排放, 保存的绝对路径
String filePath = FtpClientUtil.sendFile(MUOContext.getUserId(), originalFileName,file.getInputStream());
knowledge.setFilepath(filePath);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
knowledge.setKnowledgeId(knowledgeId);
xSmKnowledgeService.updateKnowledge(knowledge);
ModelAndView view = new ModelAndView("redirect:/{appName}/study/xsmknowledge/updateKnowledge");
return view;
}
上传的页面
<span style="font-family: Arial, Helvetica, sans-serif;"></span>
表单中enctype="multipart/form-data"的意思,是设置表单的MIME编码。默认情况,这个编码格式是application/x-www-form-urlencoded,不能用于文件上传;
只有使用了multipart/form-data,才能完整的传递文件数据,进行下面的操作.enctype="multipart/form-data"是上传二进制数据; form里面的input的值以2进制的方式传过去。
form里面的input的值以2进制的方式传过去,所以request就得不到值了。也就是说加了这段代码,用request就会传递不成功,取表单值加入数据库时,用到下面的:SmartUpload su = new SmartUpload();//新建一个SmartUpload对象su.getRequest().getParameterValues();取数组值su.getRequest().getParameter( );取单个参数单个值
<form id="kb_upload_http" enctype="multipart/form-data" action="${sys.appPath}/study/xsmknowledge/addKnowledgeFile" method="post" name="kb_upload_http"
οnsubmit="return check()">
<fieldset>
<div class="control-group">
<label class="control-label"> 上传本地文件(允许上传文件类型: doc;docx;ppt;pptx;xls;xlsx;)</label>
<div class="controls">
<input class="inputText" style="width:50%" id="upload_file_local" accept="" name="file" type="file" />
</div>
</div>
<div class="control-group">
<label class="control-label"> </label>
<div class="controls">
<button type="button" class="btn loading" οnclick="javascript:window.location.href='${sys.appPath}/study/xsmknowledge/upda teKnowledge';" name="cancle" >上一步</button>
<button class="btn btn-primary" name="submit" type="submit" >上传</button> <button type="button" class="btn" οnclick="jav ascript:art.dialog.close();" name="cancle" >取消</button>
</div>
</div><input name="_qf__kb_upload_http" type="hidden" value="" />
<input name="kb_type" type="hidden" value="file" />
<input name="knowledgeId" type="hidden" value="${list.knowledgeId }" />
<input name="id" type="hidden" value="98" />
<input name="location" type="hidden" value="http" />
<input name="MAX_FILE_SIZE" type="hidden" value="838860800" />
</fieldset>
</form>
/**
* 通过ftp上传文件/ 1.img 2.video 3.other分类排放
*
* @param userid
* @param file
* @return 保存的绝对路径
*/
public static String sendFile(String userid, String filename, InputStream in)
throws Exception {
FTPClient ftpclient = new FTPClient();
try {
if(!ftpclient.isConnected()){
ftpclient.connect(FTP_HOST, FTP_PORT);
int reply = ftpclient.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
// 连接错误的时候报错。
throw new Exception("Can't Connect to :" + FTP_HOST);
}
// 登录
if (ftpclient.login(FTP_USER, FTP_PWD) == false) {
throw new Exception("Invalid user/password");
}
// 设置传送文件模式
ftpclient.setFileType(FTP.BINARY_FILE_TYPE);
ftpclient.setControlEncoding("utf-8");
}
// 传送文件
String suffixname = filename.substring(
filename.lastIndexOf(".") + 1).toUpperCase();
String basePath = "";
switch (suffixname) {
case "MP4":
basePath = FTP_VIDEO_PATH;
break;
case "JPG":
case "PNG":
case "GIF":
case "JPGE":
case "BMP":
basePath = FTP_IMAGE_PATH;
break;
default:
basePath = FTP_OTHER_PATH;
}
String path="";
if(!ftpclient.changeWorkingDirectory(FTP_ROOT_PATH)){//如果没有change成功,表明没成功cwd
ftpclient.makeDirectory(FTP_ROOT_PATH);
ftpclient.changeWorkingDirectory(FTP_ROOT_PATH);
}
path+=File.separatorChar+FTP_ROOT_PATH;
if (!ftpclient.changeWorkingDirectory(basePath)) {// 如果没有change成功,表明没成功cwd
ftpclient.makeDirectory(basePath);
}
ftpclient.changeWorkingDirectory(basePath);
path+=File.separatorChar+basePath;
if (!ftpclient.changeWorkingDirectory(userid)) {// 如果没有change成功,表明没成功cwd
ftpclient.makeDirectory(userid);
ftpclient.changeWorkingDirectory(userid);
}
path+=File.separatorChar+userid;
String webFilePath = UUIDUtil.getUUID() + "."
+ suffixname.toLowerCase();
boolean success = ftpclient.storeFile(webFilePath, in);
if (success) {
return path + File.separatorChar
+ webFilePath;
} else {
throw new Exception("保存失败");
}
} catch (Exception e) {
throw e;
} finally {
if (in != null) {
in.close();
}
}
}
文件下载
@RequestMapping(value = "/showKnowledgeDetails")
public ModelAndView showKnowledgeDetails(String knowledgeId) {
XSmKnowledge xSmKnowledge = xSmKnowledgeService.selectKnowledgeDetailById(knowledgeId);
//把\转为/
xSmKnowledge.setFilepath(xSmKnowledge.getFilepath().replace("\\", "/"));//拼接路径
xSmKnowledge.setFilepath("http://"+nginxHost+":"+nginxPort+xSmKnowledge.getFilepath());
ModelAndView view = new ModelAndView("/mgr/showKnowledgeDetail");
view.addObject("knowledgeList", xSmKnowledge);
view.addObject("filePath", xSmKnowledge.getFilepath());
return view;
}
<a href="${sys.appPath }/study/xsmknowledge/showKnowledgeDetails?knowledgeId=${list.knowledgeId }" class="btn btn-primary" style="color:#FFF"
target="_blank">查看详细内容</a>