您的位置:首页 > 编程语言 > Java开发

文章标题

2016-10-08 20:01 471 查看

SpringMVC上传文件学习小记

今天在把Struts2,Spring , Hibernate 写的项目改成用SpringMVC的时候遇到了一些小问题,我来总结一下今天的收获。先粘上今天写的代码把。

一 配置文件

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> </bean>


这是SpringMVC上传文件的配置,里面还可以设置一些参数。例如:文件编码(defaultEncoding),文件大小(maxUploadSize)等.

然后是页面上的部分代码:

<form action="bullitinSave"  method="post" enctype="multipart/form-data">
<input name="uploadFile" type="file" />
<input name="uploadFile" type="file" />
</form>


然后是部分逻辑代码:

/**
* 系统公告保存
*
* @param resBullitin
* @return
*/
@RequestMapping("/bullitinSave")
public String bullitinSave(HttpServletRequest request, @RequestParam("uploadFile") MultipartFile[] uploadFile,Map<String, Object> model) {
try {
// 如果没有附件则返回
if (uploadFile == null || uploadFile.length == 0) {
} else {
request.setCharacterEncoding("GBK");
// 如果有附件则上传附件
String fileName = null;
for (int i = 0; i < uploadFile.length; i++) {

if (!uploadFile[i].isEmpty()) {
MultipartFile file = uploadFile[i];
fileName = new String(uploadFile[i].getOriginalFilename().getBytes(), "GBK");
String tempDir = request.getSession().getServletContext().getRealPath("/")
+ "scms\\upload\\"
+ fileName;
System.out.println("filePath:" + tempDir);
File upload = new File(tempDir);
file.transferTo(upload);
ResAnnexInfo resAnnex = annexService.saveAnnex(resBullitin.getId(), upload,
fileName);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return "/scms/common/reloadOpener";
}


写这一部分代码的时候,尤其要注意@RequestParam(“uploadFile”),这个是必须要的,而且括号里面的参数是和你上传文件的name属性是一致的。我在写上传的时候开始忘记写这个,一直报错,上传的文件接收不到,印象颇深。

在我们使用SpringMVC上传文件的时候还会用到一些API,也说一下,以后自己看起来比较方便。

getContentType()

Return the content type of the file. 返回文件的类型。例如:jpeg、txt等

getOriginalFilename()

Return the original filename in the client’s filesystem.返回从客户端上传的文件名。也就是文件的真是名称。

getInputStream()

Return an InputStream to read the contents of the file from.获取上传文件的输入流。拿到流,你也就可以干你想干的事情了。

isEmpty()

Return whether the uploaded file is empty, that is, either no file has been chosen in the multipart form or the chosen file has no content.判断文件是否为空,没有选文件,或者选得文件没有内容。这个就很好用了。你干什么总的先判断是都为空把?

transferTo(File dest)

Transfer the received file to the given destination file.把上传的文件方放到存放的目录.这个方法挺好用的,就是直接把MultipartFile转化成了File,方便了你自己读写的步骤。

还有一些别的小内容啦。

其中有(都是一些路径问题,自己经常弄混淆,记不住,所以今天记下来):

(1).request.getSession().getServletContext().getRealPath(“/”);这个是获取你的项目在磁盘上的路径。例如:Y:\eclipse\demo….

(2).request.getContextPath(); 这个是获取你项目的根目录。项目发布在服务器后都是从WebRoot或者WebContent或者公司起的名字等。从这里开始的。

以上就是我今天的收获啦, 收获还蛮大的,明天继续加油。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  spring mvc