Spring之MultipartFile传送文件示例分享

打印 上一主题 下一主题

主题 895|帖子 895|积分 2685

Spring简介:
     Spring框架是一个开放源代码的J2EE应用程序框架,由Rod Johnson发起,是针对bean的生命周期进行管理的轻量级容器(lightweight container)。 Spring解决了开发者在J2EE开发中遇到的许多常见的问题,提供了功能强大IOC、AOP及Web MVC等功能。Spring可以单独应用于构筑应用程序,也可以和Struts、Webwork、Tapestry等众多Web框架组合使用,并且可以与 Swing等桌面应用程序AP组合。因此, Spring不仅仅能应用于J2EE应用程序之中,也可以应用于桌面应用程序以及小应用程序之中。Spring框架主要由七部分组成,分别是 Spring Core、 Spring AOP、 Spring ORM、 Spring DAO、Spring Context、 Spring Web和 Spring Web MVC。
 MultipartFile是springframe封装好的一个专门用于文件上传的接口
    MultipartFile是一个接口,如下所示:
  
  1. public interface MultipartFile {
  2.     /**
  3.      * Return the name of the parameter in the multipart form.
  4.      * @return the name of the parameter (never {@code null} or empty)
  5.      */
  6.     String getName();
  7.     /**
  8.      * Return the original filename in the client's filesystem.
  9.      * <p>This may contain path information depending on the browser used,
  10.      * but it typically will not with any other than Opera.
  11.      * @return the original filename, or the empty String if no file
  12.      * has been chosen in the multipart form, or {@code null}
  13.      * if not defined or not available
  14.      */
  15.     String getOriginalFilename();
  16.     /**
  17.      * Return the content type of the file.
  18.      * @return the content type, or {@code null} if not defined
  19.      * (or no file has been chosen in the multipart form)
  20.      */
  21.     String getContentType();
  22.     /**
  23.      * Return whether the uploaded file is empty, that is, either no file has
  24.      * been chosen in the multipart form or the chosen file has no content.
  25.      */
  26.     boolean isEmpty();
  27.     /**
  28.      * Return the size of the file in bytes.
  29.      * @return the size of the file, or 0 if empty
  30.      */
  31.     long getSize();
  32.     /**
  33.      * Return the contents of the file as an array of bytes.
  34.      * @return the contents of the file as bytes, or an empty byte array if empty
  35.      * @throws IOException in case of access errors (if the temporary store fails)
  36.      */
  37.     byte[] getBytes() throws IOException;
  38.     /**
  39.      * Return an InputStream to read the contents of the file from.
  40.      * The user is responsible for closing the stream.
  41.      * @return the contents of the file as stream, or an empty stream if empty
  42.      * @throws IOException in case of access errors (if the temporary store fails)
  43.      */
  44.     InputStream getInputStream() throws IOException;
  45.     /**
  46.      * Transfer the received file to the given destination file.
  47.      * <p>This may either move the file in the filesystem, copy the file in the
  48.      * filesystem, or save memory-held contents to the destination file.
  49.      * If the destination file already exists, it will be deleted first.
  50.      * <p>If the file has been moved in the filesystem, this operation cannot
  51.      * be invoked again. Therefore, call this method just once to be able to
  52.      * work with any storage mechanism.
  53.      * @param dest the destination file
  54.      * @throws IOException in case of reading or writing errors
  55.      * @throws IllegalStateException if the file has already been moved
  56.      * in the filesystem and is not available anymore for another transfer
  57.      */
  58.     void transferTo(File dest) throws IOException, IllegalStateException;
  59. }
复制代码
commons 实现类
  1. /*
  2. * Copyright 2002-2012 the original author or authors.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. *      http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package org.springframework.web.multipart.commons;
  17. import java.io.ByteArrayInputStream;
  18. import java.io.File;
  19. import java.io.IOException;
  20. import java.io.InputStream;
  21. import java.io.Serializable;
  22. import org.apache.commons.fileupload.FileItem;
  23. import org.apache.commons.fileupload.FileUploadException;
  24. import org.apache.commons.fileupload.disk.DiskFileItem;
  25. import org.apache.commons.logging.Log;
  26. import org.apache.commons.logging.LogFactory;
  27. import org.springframework.web.multipart.MultipartFile;
  28. /**
  29. * MultipartFile implementation for Jakarta Commons FileUpload.
  30. *
  31. * @author Trevor D. Cook
  32. * @author Juergen Hoeller
  33. * @since 29.09.2003
  34. * @see CommonsMultipartResolver
  35. */
  36. @SuppressWarnings("serial")
  37. public class CommonsMultipartFile implements MultipartFile, Serializable {
  38.     protected static final Log logger = LogFactory.getLog(CommonsMultipartFile.class);
  39.     private final FileItem fileItem;
  40.     private final long size;
  41.     /**
  42.      * Create an instance wrapping the given FileItem.
  43.      * @param fileItem the FileItem to wrap
  44.      */
  45.     public CommonsMultipartFile(FileItem fileItem) {
  46.         this.fileItem = fileItem;
  47.         this.size = this.fileItem.getSize();
  48.     }
  49.     /**
  50.      * Return the underlying {@code org.apache.commons.fileupload.FileItem}
  51.      * instance. There is hardly any need to access this.
  52.      */
  53.     public final FileItem getFileItem() {
  54.         return this.fileItem;
  55.     }
  56.     @Override
  57.     public String getName() {
  58.         return this.fileItem.getFieldName();
  59.     }
  60.     @Override
  61.     public String getOriginalFilename() {
  62.         String filename = this.fileItem.getName();
  63.         if (filename == null) {
  64.             // Should never happen.
  65.             return "";
  66.         }
  67.         // check for Unix-style path
  68.         int pos = filename.lastIndexOf("/");
  69.         if (pos == -1) {
  70.             // check for Windows-style path
  71.             pos = filename.lastIndexOf("\");
  72.         }
  73.         if (pos != -1)  {
  74.             // any sort of path separator found
  75.             return filename.substring(pos + 1);
  76.         }
  77.         else {
  78.             // plain name
  79.             return filename;
  80.         }
  81.     }
  82.     @Override
  83.     public String getContentType() {
  84.         return this.fileItem.getContentType();
  85.     }
  86.     @Override
  87.     public boolean isEmpty() {
  88.         return (this.size == 0);
  89.     }
  90.     @Override
  91.     public long getSize() {
  92.         return this.size;
  93.     }
  94.     @Override
  95.     public byte[] getBytes() {
  96.         if (!isAvailable()) {
  97.             throw new IllegalStateException("File has been moved - cannot be read again");
  98.         }
  99.         byte[] bytes = this.fileItem.get();
  100.         return (bytes != null ? bytes : new byte[0]);
  101.     }
  102.     @Override
  103.     public InputStream getInputStream() throws IOException {
  104.         if (!isAvailable()) {
  105.             throw new IllegalStateException("File has been moved - cannot be read again");
  106.         }
  107.         InputStream inputStream = this.fileItem.getInputStream();
  108.         return (inputStream != null ? inputStream : new ByteArrayInputStream(new byte[0]));
  109.     }
  110.     @Override
  111.     public void transferTo(File dest) throws IOException, IllegalStateException {
  112.         if (!isAvailable()) {
  113.             throw new IllegalStateException("File has already been moved - cannot be transferred again");
  114.         }
  115.         if (dest.exists() && !dest.delete()) {
  116.             throw new IOException(
  117.                     "Destination file [" + dest.getAbsolutePath() + "] already exists and could not be deleted");
  118.         }
  119.         try {
  120.             this.fileItem.write(dest);
  121.             if (logger.isDebugEnabled()) {
  122.                 String action = "transferred";
  123.                 if (!this.fileItem.isInMemory()) {
  124.                     action = isAvailable() ? "copied" : "moved";
  125.                 }
  126.                 logger.debug("Multipart file '" + getName() + "' with original filename [" +
  127.                         getOriginalFilename() + "], stored " + getStorageDescription() + ": " +
  128.                         action + " to [" + dest.getAbsolutePath() + "]");
  129.             }
  130.         }
  131.         catch (FileUploadException ex) {
  132.             throw new IllegalStateException(ex.getMessage());
  133.         }
  134.         catch (IOException ex) {
  135.             throw ex;
  136.         }
  137.         catch (Exception ex) {
  138.             logger.error("Could not transfer to file", ex);
  139.             throw new IOException("Could not transfer to file: " + ex.getMessage());
  140.         }
  141.     }
  142.     /**
  143.      * Determine whether the multipart content is still available.
  144.      * If a temporary file has been moved, the content is no longer available.
  145.      */
  146.     protected boolean isAvailable() {
  147.         // If in memory, it's available.
  148.         if (this.fileItem.isInMemory()) {
  149.             return true;
  150.         }
  151.         // Check actual existence of temporary file.
  152.         if (this.fileItem instanceof DiskFileItem) {
  153.             return ((DiskFileItem) this.fileItem).getStoreLocation().exists();
  154.         }
  155.         // Check whether current file size is different than original one.
  156.         return (this.fileItem.getSize() == this.size);
  157.     }
  158.     /**
  159.      * Return a description for the storage location of the multipart content.
  160.      * Tries to be as specific as possible: mentions the file location in case
  161.      * of a temporary file.
  162.      */
  163.     public String getStorageDescription() {
  164.         if (this.fileItem.isInMemory()) {
  165.             return "in memory";
  166.         }
  167.         else if (this.fileItem instanceof DiskFileItem) {
  168.             return "at [" + ((DiskFileItem) this.fileItem).getStoreLocation().getAbsolutePath() + "]";
  169.         }
  170.         else {
  171.             return "on disk";
  172.         }
  173.     }
  174. }
复制代码
另一个实现类  standard 
  1. /*
  2. * Copyright 2002-2014 the original author or authors.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. *      http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package org.springframework.web.multipart.support;
  17. import java.io.File;
  18. import java.io.IOException;
  19. import java.io.InputStream;
  20. import java.util.ArrayList;
  21. import java.util.Collection;
  22. import java.util.Collections;
  23. import java.util.Enumeration;
  24. import java.util.LinkedHashMap;
  25. import java.util.LinkedHashSet;
  26. import java.util.Map;
  27. import java.util.Set;
  28. import javax.servlet.http.HttpServletRequest;
  29. import javax.servlet.http.Part;
  30. import org.springframework.http.HttpHeaders;
  31. import org.springframework.util.FileCopyUtils;
  32. import org.springframework.util.LinkedMultiValueMap;
  33. import org.springframework.util.MultiValueMap;
  34. import org.springframework.web.multipart.MultipartException;
  35. import org.springframework.web.multipart.MultipartFile;
  36. /**
  37. * Spring MultipartHttpServletRequest adapter, wrapping a Servlet 3.0 HttpServletRequest
  38. * and its Part objects. Parameters get exposed through the native request's getParameter
  39. * methods - without any custom processing on our side.
  40. *
  41. * @author Juergen Hoeller
  42. * @since 3.1
  43. */
  44. public class StandardMultipartHttpServletRequest extends AbstractMultipartHttpServletRequest {
  45.     private static final String CONTENT_DISPOSITION = "content-disposition";
  46.     private static final String FILENAME_KEY = "filename=";
  47.     private Set<String> multipartParameterNames;
  48.     /**
  49.      * Create a new StandardMultipartHttpServletRequest wrapper for the given request,
  50.      * immediately parsing the multipart content.
  51.      * @param request the servlet request to wrap
  52.      * @throws MultipartException if parsing failed
  53.      */
  54.     public StandardMultipartHttpServletRequest(HttpServletRequest request) throws MultipartException {
  55.         this(request, false);
  56.     }
  57.     /**
  58.      * Create a new StandardMultipartHttpServletRequest wrapper for the given request.
  59.      * @param request the servlet request to wrap
  60.      * @param lazyParsing whether multipart parsing should be triggered lazily on
  61.      * first access of multipart files or parameters
  62.      * @throws MultipartException if an immediate parsing attempt failed
  63.      */
  64.     public StandardMultipartHttpServletRequest(HttpServletRequest request, boolean lazyParsing) throws MultipartException {
  65.         super(request);
  66.         if (!lazyParsing) {
  67.             parseRequest(request);
  68.         }
  69.     }
  70.     private void parseRequest(HttpServletRequest request) {
  71.         try {
  72.             Collection<Part> parts = request.getParts();
  73.             this.multipartParameterNames = new LinkedHashSet<String>(parts.size());
  74.             MultiValueMap<String, MultipartFile> files = new LinkedMultiValueMap<String, MultipartFile>(parts.size());
  75.             for (Part part : parts) {
  76.                 String filename = extractFilename(part.getHeader(CONTENT_DISPOSITION));
  77.                 if (filename != null) {
  78.                     files.add(part.getName(), new StandardMultipartFile(part, filename));
  79.                 }
  80.                 else {
  81.                     this.multipartParameterNames.add(part.getName());
  82.                 }
  83.             }
  84.             setMultipartFiles(files);
  85.         }
  86.         catch (Exception ex) {
  87.             throw new MultipartException("Could not parse multipart servlet request", ex);
  88.         }
  89.     }
  90.     private String extractFilename(String contentDisposition) {
  91.         if (contentDisposition == null) {
  92.             return null;
  93.         }
  94.         // TODO: can only handle the typical case at the moment
  95.         int startIndex = contentDisposition.indexOf(FILENAME_KEY);
  96.         if (startIndex == -1) {
  97.             return null;
  98.         }
  99.         String filename = contentDisposition.substring(startIndex + FILENAME_KEY.length());
  100.         if (filename.startsWith(""")) {
  101.             int endIndex = filename.indexOf(""", 1);
  102.             if (endIndex != -1) {
  103.                 return filename.substring(1, endIndex);
  104.             }
  105.         }
  106.         else {
  107.             int endIndex = filename.indexOf(";");
  108.             if (endIndex != -1) {
  109.                 return filename.substring(0, endIndex);
  110.             }
  111.         }
  112.         return filename;
  113.     }
  114.     @Override
  115.     protected void initializeMultipart() {
  116.         parseRequest(getRequest());
  117.     }
  118.     @Override
  119.     public Enumeration<String> getParameterNames() {
  120.         if (this.multipartParameterNames == null) {
  121.             initializeMultipart();
  122.         }
  123.         if (this.multipartParameterNames.isEmpty()) {
  124.             return super.getParameterNames();
  125.         }
  126.         // Servlet 3.0 getParameterNames() not guaranteed to include multipart form items
  127.         // (e.g. on WebLogic 12) -> need to merge them here to be on the safe side
  128.         Set<String> paramNames = new LinkedHashSet<String>();
  129.         Enumeration<String> paramEnum = super.getParameterNames();
  130.         while (paramEnum.hasMoreElements()) {
  131.             paramNames.add(paramEnum.nextElement());
  132.         }
  133.         paramNames.addAll(this.multipartParameterNames);
  134.         return Collections.enumeration(paramNames);
  135.     }
  136.     @Override
  137.     public Map<String, String[]> getParameterMap() {
  138.         if (this.multipartParameterNames == null) {
  139.             initializeMultipart();
  140.         }
  141.         if (this.multipartParameterNames.isEmpty()) {
  142.             return super.getParameterMap();
  143.         }
  144.         // Servlet 3.0 getParameterMap() not guaranteed to include multipart form items
  145.         // (e.g. on WebLogic 12) -> need to merge them here to be on the safe side
  146.         Map<String, String[]> paramMap = new LinkedHashMap<String, String[]>();
  147.         paramMap.putAll(super.getParameterMap());
  148.         for (String paramName : this.multipartParameterNames) {
  149.             if (!paramMap.containsKey(paramName)) {
  150.                 paramMap.put(paramName, getParameterValues(paramName));
  151.             }
  152.         }
  153.         return paramMap;
  154.     }
  155.     @Override
  156.     public String getMultipartContentType(String paramOrFileName) {
  157.         try {
  158.             Part part = getPart(paramOrFileName);
  159.             return (part != null ? part.getContentType() : null);
  160.         }
  161.         catch (Exception ex) {
  162.             throw new MultipartException("Could not access multipart servlet request", ex);
  163.         }
  164.     }
  165.     @Override
  166.     public HttpHeaders getMultipartHeaders(String paramOrFileName) {
  167.         try {
  168.             Part part = getPart(paramOrFileName);
  169.             if (part != null) {
  170.                 HttpHeaders headers = new HttpHeaders();
  171.                 for (String headerName : part.getHeaderNames()) {
  172.                     headers.put(headerName, new ArrayList<String>(part.getHeaders(headerName)));
  173.                 }
  174.                 return headers;
  175.             }
  176.             else {
  177.                 return null;
  178.             }
  179.         }
  180.         catch (Exception ex) {
  181.             throw new MultipartException("Could not access multipart servlet request", ex);
  182.         }
  183.     }
  184.     /**
  185.      * Spring MultipartFile adapter, wrapping a Servlet 3.0 Part object.
  186.      */
  187.     private static class StandardMultipartFile implements MultipartFile {
  188.         private final Part part;
  189.         private final String filename;
  190.         public StandardMultipartFile(Part part, String filename) {
  191.             this.part = part;
  192.             this.filename = filename;
  193.         }
  194.         @Override
  195.         public String getName() {
  196.             return this.part.getName();
  197.         }
  198.         @Override
  199.         public String getOriginalFilename() {
  200.             return this.filename;
  201.         }
  202.         @Override
  203.         public String getContentType() {
  204.             return this.part.getContentType();
  205.         }
  206.         @Override
  207.         public boolean isEmpty() {
  208.             return (this.part.getSize() == 0);
  209.         }
  210.         @Override
  211.         public long getSize() {
  212.             return this.part.getSize();
  213.         }
  214.         @Override
  215.         public byte[] getBytes() throws IOException {
  216.             return FileCopyUtils.copyToByteArray(this.part.getInputStream());
  217.         }
  218.         @Override
  219.         public InputStream getInputStream() throws IOException {
  220.             return this.part.getInputStream();
  221.         }
  222.         @Override
  223.         public void transferTo(File dest) throws IOException, IllegalStateException {
  224.             this.part.write(dest.getPath());
  225.         }
  226.     }
  227. }
复制代码
编写上传示例代码
  1.         //这里用到了getOriginalFilename()方法,为了获取文件名
  2. String fileName=uploadFile.getOriginalFilename();
  3.         String fileType=fileName.substring(fileName.lastIndexOf("."));
  4.         if (! fileType.matches("^.(jpg|png|tif)$")) {
  5.          //这里的error=1时,表示操作不正常
  6.             result.setError(1);
  7.             return result;
  8.         }  
  9. try {
  10.               //这里用到了getInputStream()方法,为了将文件转换成流
  11.               //判断是否文件为恶意文件
  12.             BufferedImage bufferedImage=ImageIO.read(uploadFile.getInputStream());
  13.             int height=bufferedImage.getHeight();
  14.             int width=bufferedImage.getWidth();
  15.             if (width==0||height==0) {
  16.            //这里的error=1时,表示操作不正常
  17.                 result.setError(1);
  18.                 return result;
  19.             }   
  20.             //这里用到了transferTo()方法,进行写盘操作
  21.             //这里的path需要自己设定,这里我就没有写,只是随便写的path代表路径
  22.             uploadFile.transferTo(path);
  23.             return result;
  24.         } catch (IOException e) {
  25.             e.printStackTrace();
  26.         }
复制代码
 

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
回复

使用道具 举报

0 个回复

正序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

钜形不锈钢水箱

金牌会员
这个人很懒什么都没写!
快速回复 返回顶部 返回列表