package com.bobo.code.web.controller;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
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.multipart.MultipartFile;
@Controller@RequestMapping({
"file/*"
}) public class LoginController {
/**
* 承保文件上传
*
* @param session
*/
@RequestMapping(value = "upload.do", method = {
RequestMethod.POST,
RequestMethod.GET
}) public void fileUpload(HttpSession session, ModelMap modelMap, HttpServletResponse response, HttpServletRequest request, @RequestParam("file") MultipartFile file) throws Exception,
IOException {
String ret = "";
request.setCharacterEncoding("UTF-8"); // 编码格式处理
// 获取文件名
String fileName = file.getOriginalFilename();
System.out.println("fileName:------------------------------------------------------" + fileName);
// 获取文件大小kb
BigDecimal fileSize = new BigDecimal(file.getSize()).divide(new BigDecimal(1024), 2, BigDecimal.ROUND_HALF_UP);
String startFileName = fileName.substring(0, fileName.indexOf("."));
String endFileName = fileName.substring(fileName.lastIndexOf("."));
// 新文件名称
String newFileName = startFileName + "_" + Math.random() + endFileName;
// 文件保存路径
String parentPath = request.getSession().getServletContext().getRealPath("/") + "upload/";
String filePath = parentPath + newFileName;
System.out.println("filePath:-----------------------------------------------------------" + filePath);
System.out.println("System.setProperty(‘sun.jnu.encoding‘) --------" + System.getProperty("sun.jnu.encoding"));
System.setProperty("sun.jnu.encoding", "utf-8");
System.out.println("System.setProperty(‘sun.jnu.encoding‘) --------" + System.getProperty("sun.jnu.encoding"));
File newFile = new File(parentPath);
if (!newFile.exists()) { // 判断文件夹是否创建,没有创建则创建新文件夹
newFile.mkdirs();
}
boolean uploadFile = true;
// 比较上传文件大小是否超过10M
if (fileSize.compareTo(new BigDecimal(1024 * 10)) > 0) {
uploadFile = false;
ret = "上传文件的大小不能超过10Mb,请重新选择!";
}
if (uploadFile) {
try {
file.transferTo(new File(filePath)); // 转存文件
ret = "上传成功!";
} catch(Exception e) {
ret = "上传失败!";
}
}
try {
response.setContentType("text/html;charset=UTF-8");
response.getWriter().write(ret);
response.getWriter().flush();
} catch(IOException e) {
e.printStackTrace();
}
}
}
来源: http://www.bubuko.com/infodetail-2262658.html