1.jar导入
commons-fileupload-1.1.1.jar
commons-io-1.3.2.jar
2.配置spring-mvc-context.xml
<!-- 文件上传大小设定 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 指定所上传文件的总大小不能超过5000KB。注意maxUploadSize属性的限制不是针对单个文件,而是所有文件的容量之和 -->
<property name="maxUploadSize" value="52428800"/>
<property name="maxInMemorySize">
<value>2048</value>
</property>
</bean>
3.代码 UploadController.java
package com.ssay.sms.controller;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
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.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.ssay.common.ReturnBaseJson;
@Controller
@RequestMapping("/user")
public class UploadController {
@RequestMapping(value = "index")
public String getOne(HttpServletRequest request) {
return "index";
}
//图片上传路径
public static String UPLOAD_PATH= "/usr/Java/redPackets_2/apache-tomcat-7.0.70/upload";
/**
* SpringMVC上传方式
* @param request
* @return
* @throws Exception
* 访问图片时是使用nginx配置端口路径访问
* 如 http://img.testim.shushangsoft.com/upload/a.jpg
*/
@RequestMapping(value = "/upload/image" ,produces = "application/json; charset=utf-8" ,method = { RequestMethod.GET, RequestMethod.POST })
@ResponseBody
public Object uploadImage(HttpServletRequest request, MultipartFile upload) throws Exception {
ReturnBaseJson returnBaseJson = new ReturnBaseJson();
try {
System.out.println("springmvc文件上传...");
//上传的位置
// String path = request.getSession().getServletContext().getRealPath("/upload/");
// System.out.println(path);
Date now = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
String createTime = dateFormat.format(now);//格式化然后放入字符串中
String path =UPLOAD_PATH+"/"+createTime;
//判断该路径是否存在,如果不存在,则创建文件夹
File file = new File(path);
if (!file.exists()) {
file.mkdirs();
}
System.out.println("************************************************************************"+path);
//上传文件项
String filename = upload.getOriginalFilename();
String uuid = UUID.randomUUID().toString().replace("-", "");
String saveName = uuid + "_" + filename.substring(filename.lastIndexOf(File.separator) + 1);
upload.transferTo(new File(path, saveName));
String suffix = getSuffix(saveName);
Integer fileType = getFileType(suffix);
Map map = new HashMap();
map.put("name", createTime+"/"+saveName);
map.put("type", fileType);
returnBaseJson.setRet("200");
returnBaseJson.setMsg("上传成功!");
returnBaseJson.setData(map);
} catch (Exception e) {
returnBaseJson.setRet("201");
returnBaseJson.setMsg("数据异常!");
}
return returnBaseJson;
}
/**
* Java获取文件的后缀名。
*/
private String getSuffix(String fileName) {
//获取文件的原始名称
// String fileName = "tim.g (1).jpg";//timg (1).jpg
//获取最后一个.的位置
int lastIndexOf = fileName.lastIndexOf(".");
//获取文件的后缀名 .jpg
String suffix = fileName.substring(lastIndexOf);
System.out.println("suffix = " + suffix);
return suffix;
}
/**
* 根据后缀判断文件是图片还是音乐或者是视频
* @param suffix
* @return 2图片 3视频 0为空
*/
private Integer getFileType(String suffix) {
Integer type = 0;
String imgExt = ".jpg|.jpeg|.png|.GIF|.JPG|.PNG|.JPEG|";
String musicExt = ".mp3|.mp4|.MP3|.MP4";
String videoExt=".AVI|.MOV|.RMVB|.RM|.FLV|.MP4|.3GP|.avi|.mov|.rmvb|.rm|.flv|.mp4|.3gp";
//indexOf 返回指定字符在字符串中第一次出现处的索引,如果此字符串中没有这样的字符,则返回 -1。
//图片
if(imgExt.indexOf(suffix) >= 0){
type = 2;
}
//视频
if(videoExt.indexOf(suffix) >= 0){
type = 3;
}
return type;
}
/**
* 传统上传方式
*
* @param request
* @return
* @throws Exception
*/
/* @RequestMapping("/fileupload1")
public String fileupload1(HttpServletRequest request) throws Exception {
System.out.println("文件上传...");
//上传的位置
String path = request.getSession().getServletContext().getRealPath("/uploads/");
//判断该路径是否存在
File file = new File(path);
if (!file.exists()) {
file.mkdirs();
}
//解析request对象
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List<FileItem> items = upload.parseRequest(request);
//遍历
for (FileItem item : items) {
if (item.isFormField()) {
//普通表单向
} else {
//上传文件项
String filename = item.getName();
String uuid = UUID.randomUUID().toString().replace("-", "");
String saveName = uuid + "_" + filename.substring(filename.lastIndexOf(File.separator) + 1);
item.write(new File(path, saveName));
//删除临时文件
item.delete();
}
}
return "success";
}*/
/**
* 跨服务器上传方式
*
* @return
* @throws Exception
*/
/* @RequestMapping("/fileupload3")
public String fileupload3(MultipartFile upload) throws Exception {
System.out.println("跨服务器文件上传...");
//定义上传服务器路径
String path = "http://localhost:9090/Fileserver/uploads/";
//上传文件项
String filename = upload.getOriginalFilename();
String uuid = UUID.randomUUID().toString().replace("-", "");
String saveName = uuid + "_" + filename.substring(filename.lastIndexOf(File.separator) + 1);
//创建客户端对象
Client client = Client.create();
//和图片服务器进行连接
WebResource webResource = client.resource(path + saveName);
//上传文件
webResource.put(upload.getBytes());
return "success";
}*/
}