package com.smbea.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator; import javax.servlet.http.HttpServletRequest; import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile; import com.smbea.po.Member;
import com.smbea.utils.CommonUtils;
import com.smbea.utils.Constants; /**
* 文件上传
* @author hapday
* 2015年5月21日 下午12:03:22
*/
@Controller
@Scope(value = "prototype")
@RequestMapping(value = "/demo")
public class FileUploadController {
private static final Logger logger = Logger.getLogger(FileUploadController.class); /**
* 多文件上传
* @param name
* @param commonsMultipartFiles
* @param request
* @return
*/
@RequestMapping(value = "/file/fileUpload1", method = RequestMethod.POST)
public @ResponseBody String fileUpload1(@RequestParam("name") String name,
@RequestParam("fileToUpload") CommonsMultipartFile [] commonsMultipartFiles, HttpServletRequest request) {
long startTime = System.currentTimeMillis();
logger.info("FileUploadController-fileUpload1-startTime=" + startTime); if(null == commonsMultipartFiles || 0 == commonsMultipartFiles.length){
return Constants.FAILURE;
} for(int index = 0, length = commonsMultipartFiles.length; index < length; index++){
CommonsMultipartFile commonsMultipartFile = commonsMultipartFiles[index]; if(null == commonsMultipartFile || commonsMultipartFile.isEmpty()){
continue;
} String originalFilename = commonsMultipartFile.getOriginalFilename();
String contentType = commonsMultipartFile.getContentType();
String fileName = commonsMultipartFile.getName();
long fileSize = commonsMultipartFile.getSize(); logger.info("name = " + name + ", originalFilename = " + originalFilename
+ ", contentType = " + contentType + ", fileName = " + fileName
+ ", fileSize = " + fileSize); // String extensionName = originalFilename.substring(originalFilename.indexOf(".")); // 扩展名
String newFileName = CommonUtils.UUIDGenerator() + "_" + originalFilename;
String destinationPath = request.getSession().getServletContext().getRealPath("/upload/" + newFileName); // 存放位置
logger.info("destinationPath = " + destinationPath);
File destFile = new File(destinationPath); try {
FileUtils.copyInputStreamToFile(commonsMultipartFile.getInputStream(), destFile);
} catch (IOException e) {
e.printStackTrace();
} Member member = new Member();
member.setName(name);
// member.setPhotoPath("/upload/" + newFileName);
} logger.info("FileUploadController-fileUpload1-耗时=" + (System.currentTimeMillis() - startTime));
return Constants.SUCCESS;
} @RequestMapping(value = "/file/fileUpload2", method = RequestMethod.POST)
public @ResponseBody String fileUpload2(@RequestParam("name") String name,
HttpServletRequest request) {
long startTime = System.currentTimeMillis();
logger.info("FileUploadController-fileUpload2-startTime=" + startTime); MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
MultipartFile multipartFile = multipartRequest.getFile("fileToUpload");
// CommonsMultipartFile commonsMultipartFile = (CommonsMultipartFile) multipartRequest; if(null == multipartFile){
return Constants.FAILURE;
} String originalFilename = multipartFile.getOriginalFilename();
String contentType = multipartFile.getContentType();
String fileName = multipartFile.getName();
long fileSize = multipartFile.getSize(); logger.info("name = " + name + ", originalFilename = " + originalFilename
+ ", contentType = " + contentType + ", fileName = " + fileName
+ ", fileSize = " + fileSize); // String extensionName = originalFilename.substring(originalFilename.indexOf(".")); // 扩展名
String newFileName = CommonUtils.UUIDGenerator() + "_" + originalFilename;
String destinationPath = request.getSession().getServletContext().getRealPath("/upload/" + newFileName); // 存放位置
logger.info("destinationPath = " + destinationPath);
File destFile = new File(destinationPath); try {
FileUtils.copyInputStreamToFile(multipartFile.getInputStream(), destFile);
} catch (IOException e) {
e.printStackTrace();
} Member member = new Member();
member.setName(name);
// member.setPhotoPath("/upload/" + newFileName); logger.info("FileUploadController-fileUpload2-耗时=" + (System.currentTimeMillis() - startTime));
return Constants.SUCCESS;
} /**
* 文件上传
* @param name
* @param commonsMultipartFiles
* @param request
* @return
*/
@RequestMapping(value = "/file/fileUpload3", method = RequestMethod.POST)
public @ResponseBody String fileUpload3(@RequestParam("name") String name,
@RequestParam("fileToUpload") CommonsMultipartFile commonsMultipartFile, HttpServletRequest request) {
long startTime = System.currentTimeMillis();
logger.info("FileUploadController-fileUpload1-startTime=" + startTime); if(null == commonsMultipartFile){
return Constants.FAILURE;
} String originalFileName = commonsMultipartFile.getOriginalFilename();
String contentType = commonsMultipartFile.getContentType();
String fileName = commonsMultipartFile.getName();
long fileSize = commonsMultipartFile.getSize(); logger.info("name = " + name + ", originalFilename = " + originalFileName
+ ", contentType = " + contentType + ", fileName = " + fileName
+ ", fileSize = " + fileSize); // String extensionName = originalFilename.substring(originalFilename.indexOf(".")); // 扩展名
String newFileName = CommonUtils.UUIDGenerator() + "_" + originalFileName;
String destinationPath = request.getSession().getServletContext().getRealPath("/upload/" + newFileName); // 存放位置
logger.info("destinationPath = " + destinationPath);
File destFile = new File(destinationPath); try {
FileUtils.copyInputStreamToFile(commonsMultipartFile.getInputStream(), destFile);
} catch (IOException e) {
e.printStackTrace();
} Member member = new Member();
member.setName(name);
// member.setPhotoPath("/upload/" + newFileName); logger.info("FileUploadController-fileUpload3-耗时=" + (System.currentTimeMillis() - startTime));
return Constants.SUCCESS;
} @RequestMapping(value = "/file/fileUpload4", method = RequestMethod.POST)
public @ResponseBody String fileUpload4(@RequestParam("name") String name, @RequestParam("fileToUpload") CommonsMultipartFile commonsMultipartFile,
HttpServletRequest request) {
long startTime = System.currentTimeMillis();
logger.info("FileUploadController-fileUpload4-startTime=" + startTime); if(null == commonsMultipartFile){
return Constants.FAILURE;
} String originalFilename = commonsMultipartFile.getOriginalFilename();
String contentType = commonsMultipartFile.getContentType();
String fileName = commonsMultipartFile.getName();
long fileSize = commonsMultipartFile.getSize(); logger.info("name = " + name + ", originalFilename = " + originalFilename
+ ", contentType = " + contentType + ", fileName = " + fileName
+ ", fileSize = " + fileSize); // String extensionName = originalFilename.substring(originalFilename.indexOf(".")); // 扩展名
String newFileName = CommonUtils.UUIDGenerator() + "_" + originalFilename;
String destinationPath = request.getSession().getServletContext().getRealPath("/upload/" + newFileName); // 存放位置
logger.info("destinationPath = " + destinationPath);
File destFile = new File(destinationPath); try {
FileUtils.copyInputStreamToFile(commonsMultipartFile.getInputStream(), destFile);
} catch (IOException e) {
e.printStackTrace();
} Member member = new Member();
member.setName(name);
// member.setPhotoPath("/upload/" + newFileName); logger.info("FileUploadController-fileUpload4-耗时=" + (System.currentTimeMillis() - startTime));
return Constants.SUCCESS;
} /**
* 多文件上传
* @param name
* @param multipartRequest
* @param request
* @return
*/
@RequestMapping(value = "/file/fileUpload5", method = RequestMethod.POST)
public @ResponseBody String fileUpload5(@RequestParam("name") String name,
HttpServletRequest request) {
long startTime = System.currentTimeMillis();
logger.info("FileUploadController-fileUpload5-startTime=" + startTime); MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; if(null == multipartRequest || !multipartRequest.getFileNames().hasNext()){
return Constants.FAILURE;
} for (Iterator<?> fileIterator = multipartRequest.getFileNames(); fileIterator.hasNext();) {
String key = (String) fileIterator.next();
MultipartFile multipartFile = multipartRequest.getFile(key); if(null == multipartFile || 0 == multipartFile.getSize()){
continue;
} String originalFilename = multipartFile.getOriginalFilename();
String contentType = multipartFile.getContentType();
String fileName = multipartFile.getName();
long fileSize = multipartFile.getSize(); logger.info("name = " + name + ", originalFilename = "
+ originalFilename + ", contentType = " + contentType
+ ", fileName = " + fileName + ", fileSize = " + fileSize); String newFileName = CommonUtils.UUIDGenerator() + "_"
+ originalFilename; String fileUploadPath = multipartRequest.getSession()
.getServletContext()
.getRealPath(Constants.FILE_UPLOAD_PATH); logger.info("fileUploadPath = " + fileUploadPath); try {
this.saveFileFromInputStream(multipartFile.getInputStream(),
fileUploadPath, newFileName);
} catch (Exception e) {
e.printStackTrace();
} Member member = new Member();
member.setName(name);
// member.setPhotoPath(Constants.FILE_UPLOAD_PATH + newFileName);
} logger.info("FileUploadController-fileUpload5-耗时=" + (System.currentTimeMillis() - startTime));
return Constants.SUCCESS;
} @RequestMapping(value = "/file/fileUpload6", method = RequestMethod.POST)
public @ResponseBody String fileUpload6(@RequestParam("name") String name, MultipartHttpServletRequest multipartRequest,
HttpServletRequest request) {
long startTime = System.currentTimeMillis();
logger.info("FileUploadController-fileUpload6-startTime=" + startTime); // MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
// MultipartFile multipartFile = multipartRequest.getFile("fileToUpload");
// CommonsMultipartFile commonsMultipartFile = (CommonsMultipartFile) multipartRequest; if(null == multipartRequest || !multipartRequest.getFileNames().hasNext()){
return Constants.FAILURE;
} for (Iterator<?> fileIterator = multipartRequest.getFileNames(); fileIterator.hasNext();) {
String key = (String) fileIterator.next();
MultipartFile multipartFile = multipartRequest.getFile(key); if(null == multipartFile || 0 == multipartFile.getSize()){
continue;
} String originalFilename = multipartFile.getOriginalFilename();
String contentType = multipartFile.getContentType();
String fileName = multipartFile.getName();
long fileSize = multipartFile.getSize(); logger.info("name = " + name + ", originalFilename = "
+ originalFilename + ", contentType = " + contentType
+ ", fileName = " + fileName + ", fileSize = " + fileSize); String newFileName = CommonUtils.UUIDGenerator() + "_"
+ originalFilename; String fileUploadPath = multipartRequest.getSession()
.getServletContext()
.getRealPath(Constants.FILE_UPLOAD_PATH); logger.info("fileUploadPath = " + fileUploadPath); try {
this.saveFileFromInputStream(multipartFile.getInputStream(),
fileUploadPath, newFileName);
} catch (Exception e) {
e.printStackTrace();
} Member member = new Member();
member.setName(name);
// member.setPhotoPath(Constants.FILE_UPLOAD_PATH + newFileName);
} logger.info("FileUploadController-fileUpload6-耗时=" + (System.currentTimeMillis() - startTime));
return Constants.SUCCESS;
} /**
* 保存文件到制定目录
* @param inputStream
* @param fileUploadPath
* @param newFileName
* @throws IOException
*/
private void saveFileFromInputStream(InputStream inputStream, String fileUploadPath,
String newFileName) throws IOException {
File file = new File(fileUploadPath, newFileName); if(!file.exists()){
file.createNewFile();
} FileOutputStream fileOutputStream = new FileOutputStream(file);
byte[] buffer = new byte[1024 * 1024];
int bytesum = 0;
int byteread = 0;
while ((byteread = inputStream.read(buffer)) != -1) {
bytesum += byteread;
fileOutputStream.write(buffer, 0, byteread);
fileOutputStream.flush();
}
fileOutputStream.close();
inputStream.close(); logger.info("*** bytesum = " + bytesum);
}
}

  

Spring文件上传Demo的更多相关文章

  1. spring文件上传

    Spring文件上传 1,导包: <dependency> <groupId>javax.servlet</groupId> <artifactId>s ...

  2. Spring 文件上传MultipartFile 执行流程分析

    在了解Spring 文件上传执行流程之前,我们必须知道两点: 1.Spring 文件上传是基于common-fileUpload 组件的,所以,文件上传必须引入此包 2.Spring 文件上传需要在X ...

  3. Spring文件上传出错:java.lang.ClassCastException: org.apache.catalina.connector.Request

    java.lang.ClassCastException: org.apache.catalina.connector.RequestFacade cannot be cast to org.spri ...

  4. Spring文件上传配置

    增加依赖jar包 <dependency> <groupId>commons-fileupload</groupId> <artifactId>comm ...

  5. Spring 文件上传功能

    本篇文章,我们要来做一个Spring的文件上传功能: 1. 创建一个Maven的web工程,然后配置pom.xml文件,增加依赖: <dependency> <groupId> ...

  6. WebSite 文件上传Demo

    知识点: 1 <!--上传文件时:        1.必须使用Post方式来提交数据        2.必须设置表单的enctype属性        3.必须在表单中包含文件域.input t ...

  7. shutil模块和几种文件上传Demo

    一.shutil模块 1.介绍 shutil模块是对os中文件操作的补充.--移动 复制 打包 压缩 解压 2.基本使用 1. shutil.copyfileobj(文件1, 文件2, 长度) 将文件 ...

  8. (转)Spring文件上传,包括一次选中多个文件

    背景: http://www.cnblogs.com/lixuwu/p/8495275.html已经实现了单文件的上传和下载,多文件的上传是另一种情景,这里记录下来 实现过程 先说前台. 运行以后就是 ...

  9. 基于tornado的文件上传demo

    这里,web框架是tornado的4.0版本,文件上传组件,是用的bootstrap-fileinput. 这个小demo,是给合作伙伴提供的,模拟APP上摄像头拍照,上传给后台服务进行图像识别用,识 ...

随机推荐

  1. uoj#119. 【UR #8】决战圆锥曲线(线段树+复杂度分析)

    题解 传送门 题解 然而要我来说我感觉只是个爆搜啊-- //minamoto #include<bits/stdc++.h> #define R register #define ll l ...

  2. JDK源码 Integer.bitCount(i)

    1.问题:输入一个整数,输出该数二进制表示中1的个数.其中负数用补码表示. 2.解决方法很多,JDK提供了一种,如下图 /** * Returns the number of one-bits in ...

  3. POJ3050 -- Hopscotch 简单的dfs搜索

    原题链接:http://poj.org/problem?id=3050 (一些文字过会儿再说现在有事儿) #include <cstdio> #include <set> us ...

  4. ArrayList深度分析:ArrayList和数组间的相互转换

    一.ArrayList转换为数组ArrayList提供public <T> T[] toArray(T[] a)方法返回一个按照正确的顺序包含此列表中所有元素的数组,返回数组的运行时类型就 ...

  5. 「杂录」CQOI 2018 背板记

    背景 经过一天天的等待,终于迎来了\(CQOI2018\),想想\(NOIp\)过后到现在,已经有了快要半年了,曾经遥遥无期,没想到时间一转眼就过去了-- 日志 \(Day0\) 因为明天就要考试了, ...

  6. svg path 路径

    许多字母命令(例如:M m)(但不是全部)成对.有一个大写和一个小写版本.大写版本是绝对版本,小写是相对版本.让我们继续以M为例: M 100,100 意思是“拿起笔并将其移动到确切的坐标100,10 ...

  7. [TJOI2017]DNA (FFT)

    [Luogu3763] FFT做字符串匹配即可,详见代码 // luogu-judger-enable-o2 #include<cstdio> #include<cstring> ...

  8. vs 部署SharePoint项目时, package丢失

    bug描述:vs部署sharepoint项目时报错:重启iis应用池失败,未将对象设置引用到实例. 解决方案:查看项目文件(包括隐藏文件),发现package文件不见了,在回收站内能找到被删除的pac ...

  9. day14 面向对象

    . 面向对象和面向过程 .面向过程:核心是过程,是流水线 优缺点: .流程化,编写简单 .可扩展性差 .面向对象:核心是对象(对象:具有相同属性和动作的结合体) 优缺点: .可扩展行强 .复杂度高于面 ...

  10. asp.net搭建项目架构

    项目的架构决定这个项目的好坏. 今天我说说传统三层架构的搭建 第一步 创建一个解决方案 例如 TaskSystem 接着这个解决方案下创建六个项目分别: TaskSystem.DAL TaskSyst ...