commonsmultipartfile api的getfile什么作用

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
您的访问请求被拒绝 403 Forbidden - ITeye技术社区
您的访问请求被拒绝
亲爱的会员,您的IP地址所在网段被ITeye拒绝服务,这可能是以下两种情况导致:
一、您所在的网段内有网络爬虫大量抓取ITeye网页,为保证其他人流畅的访问ITeye,该网段被ITeye拒绝
二、您通过某个代理服务器访问ITeye网站,该代理服务器被网络爬虫利用,大量抓取ITeye网页
请您点击按钮解除封锁&用spring MVC上传文件,都是MultipartFile,如何转化成File - 开源中国社区
当前访客身份:游客 [
当前位置:
如题,上传附件的时候我先要去判断文件的哈希值,如果附件中已经有,就不需要上传,用之前的。
我需要把MultipartFile转换成File类型。
网上查阅有2中方式,一种是MultipartFile自带的transferto
这个方法可以转,但是。。。。文件直接就上传上去了。。。我还判断哈希个毛线?。。。
第二种,spring 配置
&bean id=&multipartResolver& class=&org.springframework.monsMultipartResolver&&
&property name=&maxUploadSize& value=&&/&
&property name=&maxInMemorySize& value=&4096&/&
&/bean& 然后(File)xxx强转
但是尝试后,还是报转换类型错误
http://www.oschina.net/question/
在线等大神求解,感激不尽!!!!!!!!!
共有4个答案
<span class="a_vote_num" id="a_vote_num_
FileOutputStream fos = FileUtils.openOutputStream(new File(dir + fileName));
IOUtils.copy(
MultipartFile
.getInputStream(), fos);
--- 共有 3 条评论 ---
: 好吧。。。是传到服务器了。。换个说法。。不用保存文件了。。。是么
(2年前)&nbsp&
: 。。。。服了你了。转二进制流,难道文件就没上传到服务器么?
(2年前)&nbsp&
虽然我自己已经解决了....
思路跟你差不多吧,转二进制流。
就勾你了!
(2年前)&nbsp&
<span class="a_vote_num" id="a_vote_num_
& & & & Map&String, MultipartFile& files = mureq.getFileMap();
& & & & if (files == null || files.size() == 0) {
& & & & & & throw new RuntimeException(&no file&);
& & & & User user = (User) request.getAttribute(CommScheme.USER.getName());
& & & & Map.Entry&String, MultipartFile& e = files.entrySet().iterator().next();
& & & & MultipartFile file = e.getValue();
<span class="a_vote_num" id="a_vote_num_
& & & & MultipartHttpServletRequest mureq = (MultipartHttpServletRequest)
Map&String, MultipartFile& files = mureq.getFileMap();& & & & & if (files == null || files.size() == 0) {& & & & & & & throw new RuntimeException(&no file&);& & & & & }& & & & & User user = (User) request.getAttribute(CommScheme.USER.getName());& & & & & Map.Entry&String, MultipartFile& e = files.entrySet().iterator().next();& & & & & MultipartFile file = e.getValue();&
<span class="a_vote_num" id="a_vote_num_
文件不上传到服务器,你怎么能生成 hash值??
另一种方案是 客户端生成 hash 值,先请求检测一次,如服务器端没有,再进行上传。如果有了直接提示上传成功。当然web客户端生成 hash 值好像也不好做吧。js 没办法访问本地磁盘。
--- 共有 3 条评论 ---
我知道啊。我服务器端,接收到File对象,我就可以算出它的hash值了,不一定要保存文件啊。我是先判断hash值存不存在,然后选择保存或不保存,如果先存了再去查hash值,还有什么意义呢?
虽然这个问题我已经解决了。我直接转二进制流搞了,省的麻烦
(2年前)&nbsp&
: 那按我前面说的就可以了,先请求一次只提交 hash 值检测就行了。
(2年前)&nbsp&
/satazor/SparkMD5
/questions/768268/how-to-calculate-md5-hash-of-a-file-using-javascript
(2年前)&nbsp&
更多开发者职位上
有什么技术问题吗?
程序员J...的其它问题
类似的话题98050人阅读
Java(22)
Spring框架(3)
基本的SpringMVC的搭建在我的上一篇文章里已经写过了,这篇文章主要说明一下如何使用SpringMVC进行表单上的文件上传以及多个文件同时上传的步骤
SpringMVC 基础教程 框架分析:
SpringMVC 基础教程 简单入门实例:
文件上传项目的源码下载地址:
一、配置文件:
SpringMVC 用的是 的MultipartFile来进行文件上传 所以我们首先要配置MultipartResolver:用于处理表单中的file
&!-- 配置MultipartResolver 用于文件上传 使用spring的CommosMultipartResolver --&
&beans:bean id=&multipartResolver& class=&org.springframework.monsMultipartResolver&
p:defaultEncoding=&UTF-8&
p:maxUploadSize=&5400000&
p:uploadTempDir=&fileUpload/temp&
&/beans:bean&
其中属性详解:
defaultEncoding=&UTF-8& 是请求的编码&#26684;式,默认为iso-8859-1
maxUploadSize=&5400000& 是上传文件的大小,单位为字节
uploadTempDir=&fileUpload/temp& 为上传文件的临时路径
二、创建一个简单的上传表单:
&h2&文件上传实例&/h2&
&form action=&fileUpload.html& method=&post& enctype=&multipart/form-data&&
选择文件:&input type=&file& name=&file&&
&input type=&submit& value=&提交&&
注意要在form标签中加上enctype=&multipart/form-data&表示该表单是要处理文件的,这是最基本的东西,很多人会忘记然而当上传出错后则去找程序的错误,却忘了这一点
三、编写上传控制类
1、创建一个控制类: FileUploadController和一个返回结果的页面list.jsp
2、编写提交表单的action:
//通过Spring的autowired注解获取spring默认配置的request
@Autowired
private HttpServletR
* 上传文件 用@RequestParam注解来指定表单上的file为MultipartFile
* @param file
@RequestMapping(&fileUpload&)
public String fileUpload(@RequestParam(&file&) MultipartFile file) {
// 判断文件是否为空
if (!file.isEmpty()) {
// 文件保存路径
String filePath = request.getSession().getServletContext().getRealPath(&/&) + &upload/&
+ file.getOriginalFilename();
// 转存文件
file.transferTo(new File(filePath));
} catch (Exception e) {
e.printStackTrace();
return &redirect:/list.html&;
* 读取上传文件中得所有文件并返回
@RequestMapping(&list&)
public ModelAndView list() {
String filePath = request.getSession().getServletContext().getRealPath(&/&) + &upload/&;
ModelAndView mav = new ModelAndView(&list&);
File uploadDest = new File(filePath);
String[] fileNames = uploadDest.list();
for (int i = 0; i & fileNames. i++) {
//打印出文件名
System.out.println(fileNames[i]);
3、使用SpringMVC注解RequestParam来指定表单中的file参数;
4、指定一个用于保存文件的web项目路径
5、通过MultipartFile的transferTo(File dest)这个方法来转存文件到指定的路径。
到此基本的文件上传就结束了。
MultipartFile类常用的一些方法:
String getContentType()//获取文件MIME类型
InputStream getInputStream()//后去文件流
String getName() //获取表单中文件组件的名字
String getOriginalFilename() //获取上传文件的原名
long getSize()
//获取文件的字节大小,单位byte
boolean isEmpty() //是否为空
void transferTo(File dest)
//保存到一个目标文件中。
四、多文件上传。
多文件上传其实很简单,和上传其他相同的参数如checkbox一样,表单中使用相同的名称,然后action中将MultipartFile参数类定义为数组就可以。
接下来实现:
1、创建一个上传多文件的表单:
&h2&上传多个文件 实例&/h2&
&form action=&filesUpload.html& method=&post&
enctype=&multipart/form-data&&
选择文件:&input type=&file& name=&files&&
选择文件:&input type=&file& name=&files&&
选择文件:&input type=&file& name=&files&&
&input type=&submit& value=&提交&&
2、编写处理表单的action,将原来保存文件的方法单独写一个方法出来方便共用:
* 保存文件
* @param file
private boolean saveFile(MultipartFile file) {
// 判断文件是否为空
if (!file.isEmpty()) {
// 文件保存路径
String filePath = request.getSession().getServletContext().getRealPath(&/&) + &upload/&
+ file.getOriginalFilename();
// 转存文件
file.transferTo(new File(filePath));
} catch (Exception e) {
e.printStackTrace();
3、编写action:
@RequestMapping(&filesUpload&)
public String filesUpload(@RequestParam(&files&) MultipartFile[] files) {
//判断file数组不能为空并且长度大于0
if(files!=null&&files.length&0){
//循环获取file数组中得文件
for(int i = 0;i&files.i++){
MultipartFile file = files[i];
//保存文件
saveFile(file);
return &redirect:/list.html&;
最后运行项目上传文件:
参考知识库
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:731229次
积分:4124
积分:4124
排名:第5040名
原创:39篇
转载:17篇
评论:172条
(1)(1)(1)(1)(1)(3)(3)(9)(3)(4)(4)(1)(1)(1)(5)(4)(3)(3)(1)(7)Spring Framework example -
CommonsMultipartFile.java - illegalstateexception, io, ioexception, ioexception, string, string
home&|&career&|&drupal&|&java&|&mac&|&mysql&|&perl&|&scala&|&uml&|&unix
Spring Framework example source code file (CommonsMultipartFile.java)
This example
source code file (CommonsMultipartFile.java) is included in the
&& project. The intent of this project is to help you &Learn Java by Example& TM.
The Spring Framework CommonsMultipartFile.java source code
* Copyright
the original author or authors.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
package org.springframework.
import java.io.ByteArrayInputS
import java.io.F
import java.io.IOE
import java.io.InputS
import java.io.S
import mons.fileupload.FileI
import mons.fileupload.FileUploadE
import mons.fileupload.disk.DiskFileI
import mons.logging.L
import mons.logging.LogF
import org.springframework.web.multipart.MultipartF
* MultipartFile implementation for Jakarta Commons FileUpload.
* &p&NOTE: As of Spring 2.0, this class requires Commons FileUpload 1.1
* or higher. The implementation does not use any deprecated FileUpload 1.0 API
* anymore, to be compatible with future Commons FileUpload releases.
* @author Trevor D. Cook
* @author Juergen Hoeller
* @since 29.09.2003
* @see CommonsMultipartResolver
public class CommonsMultipartFile implements MultipartFile, Serializable {
protected static final Log logger = LogFactory.getLog(CommonsMultipartFile.class);
private final FileItem fileI
* Create an instance wrapping the given FileItem.
* @param fileItem the FileItem to wrap
public CommonsMultipartFile(FileItem fileItem) {
this.fileItem = fileI
this.size = this.fileItem.getSize();
* Return the underlying &code&mons.fileupload.FileItem
* instance. There is hardly any need to access this.
public final FileItem getFileItem() {
return this.fileI
public String getName() {
return this.fileItem.getFieldName();
public String getOriginalFilename() {
String filename = this.fileItem.getName();
if (filename == null) {
// Should never happen.
return "";
// check for Unix-style path
int pos = filename.lastIndexOf("/");
if (pos == -1) {
// check for Windows-style path
pos = filename.lastIndexOf("\\");
if (pos != -1)
// any sort of path separator found
return filename.substring(pos + 1);
// plain name
public String getContentType() {
return this.fileItem.getContentType();
public boolean isEmpty() {
return (this.size == 0);
public long getSize() {
return this.
public byte[] getBytes() {
if (!isAvailable()) {
throw new IllegalStateException("File has been moved - cannot be read again");
byte[] bytes = this.fileItem.get();
return (bytes != null ? bytes : new byte[0]);
public InputStream getInputStream() throws IOException {
if (!isAvailable()) {
throw new IllegalStateException("File has been moved - cannot be read again");
InputStream inputStream = this.fileItem.getInputStream();
return (inputStream != null ? inputStream : new ByteArrayInputStream(new byte[0]));
public void transferTo(File dest) throws IOException, IllegalStateException {
if (!isAvailable()) {
throw new IllegalStateException("File has already been moved - cannot be transferred again");
if (dest.exists() && !dest.delete()) {
throw new IOException(
"Destination file [" + dest.getAbsolutePath() + "] already exists and could not be deleted");
this.fileItem.write(dest);
if (logger.isDebugEnabled()) {
String action = "transferred";
if (!this.fileItem.isInMemory()) {
action = isAvailable() ? "copied" : "moved";
logger.debug("Multipart file '" + getName() + "' with original filename [" +
getOriginalFilename() + "], stored " + getStorageDescription() + ": " +
action + " to [" + dest.getAbsolutePath() + "]");
catch (FileUploadException ex) {
throw new IllegalStateException(ex.getMessage());
catch (IOException ex) {
catch (Exception ex) {
logger.error("Could not transfer to file", ex);
throw new IOException("Could not transfer to file: " + ex.getMessage());
* Determine whether the multipart content is still available.
* If a temporary file has been moved, the content is no longer available.
protected boolean isAvailable() {
// If in memory, it's available.
if (this.fileItem.isInMemory()) {
// Check actual existence of temporary file.
if (this.fileItem instanceof DiskFileItem) {
return ((DiskFileItem) this.fileItem).getStoreLocation().exists();
// Check whether current file size is different than original one.
return (this.fileItem.getSize() == this.size);
* Return a description for the storage location of the multipart content.
* Tries to be as specific as possible: mentions the file location in case
* of a temporary file.
public String getStorageDescription() {
if (this.fileItem.isInMemory()) {
return "in memory";
else if (this.fileItem instanceof DiskFileItem) {
return "at [" + ((DiskFileItem) this.fileItem).getStoreLocation().getAbsolutePath() + "]";
return "on disk";
Other Spring Framework examples (source code examples)
Here is a short list of links related to this Spring Framework CommonsMultipartFile.java source code file:
new blog posts
Alvin Alexander,
All Rights Reserved.
A percentage of advertising revenue from
pages under the
URI on this website is
paid back to open source projects.}

我要回帖

更多关于 spring multipartfile 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信