ecplise
jdk 1.8
pom.xml 文件引入以来依赖
2、springboot 启动类Application
增加@EnableAutoConfiguration(exclude = {MultipartAutoConfiguration.class})
3、application.yml文件
增加文件大小限制,上传的根目录
multipart:
enabled: true
max-file-size: 50mb
max-request-size: 50mb
上传的根目录
#公用变量,方便更改
publicvariable:
#项目图片保存路径
imglocation: /Users/wangdeqiu/Documents/fileUpload
$(function () {
$("#upload").click(function () {
var fileObj = document.getElementById("file").files[0]; // js 获取文件对象
var tokenv="ssssssss";
//var data = {"token":token,"file":fileObj};
var formData = new FormData();
formData.append("file",fileObj);
formData.append("token",tokenv);
$.ajax({
url: 'http://localhost:8080/test/upload',
type: 'POST',
cache: false,
data: new FormData($('#uploadForm')[0]),
processData: false,
contentType: false
}).done(function(res) {
//打印返回值信息
alert(res);
}).fail(function(res) {
alert("上传失败");
});
});
});
@Controller
@RequestMapping("test")
public class TestBootController {
//日志打印
private final Logger log = LoggerFactory.getLogger(TestBootController.class);
@Autowired
private FileUploadService fileUploadService;
Logger logger = LoggerFactory.getLogger(TestBootController.class);
@RequestMapping("/")
public String home() {
return "app/index";
}
@RequestMapping(value = "/upload", method = RequestMethod.POST)
@ResponseBody
public Map
Map
String fileName = file.getOriginalFilename();
System.out.println("获取....fileName.."+fileName);
try {
String fileType = "合同";
UploadFile fileEntity = fileUploadService.uploadFile(file,fileType);
System.out.println("setfileName显示的文件名"+fileEntity.getFileName());
System.out.println("setFilePath文件路径"+fileEntity.getFilePath());
System.out.println("setRealName真正的文件名"+fileEntity.getRealName());
System.out.println("setSuffix文件后缀"+fileEntity.getSuffix());
} catch (IllegalStateException e) {
logger.error("文件上传错误", e.getMessage());
e.printStackTrace();
throw e;
} catch (IOException e) {
logger.error("文件上传错误", e.getMessage());
e.printStackTrace();
} catch (Exception e) {
output.put("msg", "上传失败");
e.printStackTrace();
}
return output;
}
}
2、Servie 文件上传
package com.haidaipuhui.service.common;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import com.haidaipuhui.domain.common.UploadFile;
import com.haidaipuhui.util.FileUploadUtil;
/**
* @date 2018年7月30日 下午2:06:39
* 类说明:文件的上传与下载
*/
@Service
public class FileUploadService {
@Value("${publicvariable.imglocation}")
private String rootPath;//文件根路径
/**
*
* Desc:文件上传
* @author wangdeqiu
* @date 2018年7月30日 下午2:08:33
* @return
* @param file 上传的文件
* @param fileType 根据累心创建文件夹 例如:合同,企业资料。
* @throws Exception
*/
public UploadFile uploadFile(MultipartFile file,String fileType) throws Exception {
UploadFile fileEntity = new UploadFile();
if (file.isEmpty() || StringUtils.isBlank(file.getOriginalFilename())) {
throw new Exception();
}
String[] fileItem = file.getOriginalFilename().split("\\.");
String uuid_name = UUID.randomUUID().toString();
String relativePath = FileUploadUtil.getUploadPath()+FileUploadUtil.flag;
String filePath = rootPath+"/"+fileType+"/"+relativePath+uuid_name+"."+fileItem[1];
String path = rootPath+"/"+fileType+"/"+relativePath;//根目录+类型+时间
// File targetFile = new File(path);
// if(!targetFile.exists()){
// targetFile.mkdirs();
// }
// file.transferTo(targetFile);
File tarFile = new File(path);
if (!tarFile.exists()) {
tarFile.mkdirs();
}
String fileName = uuid_name+"."+fileItem[1];
FileInputStream fileInputStream = (FileInputStream) file.getInputStream();
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(path + File.separator + fileName));
byte[] bs = new byte[1024];
int len;
while ((len = fileInputStream.read(bs)) != -1) {
bos.write(bs, 0, len);
}
bos.flush();
bos.close();
fileEntity.setFileName(fileItem[0]);
fileEntity.setRealName(uuid_name);
fileEntity.setFilePath(relativePath);
fileEntity.setSuffix(fileItem[1]);
return fileEntity;
}
}
3、FileUploadUtil
package com.haidaipuhui.util;
import java.util.Calendar;
import java.util.Date;
public class FileUploadUtil {
public static final String flag = "/";
/**
* @title getUploadPath
* @Description: 获取日月年文件夹路径
*/
public static String getUploadPath(){
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
String yearPath = Integer.toString(calendar.get(Calendar.YEAR));
String monthPath = Integer.toString(calendar.get(Calendar.MONTH)+1);
String datePath = Integer.toString(calendar.get(Calendar.DAY_OF_MONTH));
return flag+yearPath+flag+monthPath+flag+datePath+flag;
}
}