@RequestMapping(value = "upload", method = RequestMethod.POST)
@ResponseBody
public String upload(HttpServletRequest request,
HttpServletResponse response)
{
Result rt= new Result();
response.setContentType("text/html;charset=utf-8");
// 将请求消息中的每一个项目封装成单独的DiskFileItem(FileItem接口的具体实现)的工作
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(4096);
ServletFileUpload sfu = new ServletFileUpload(factory);
sfu.setHeaderEncoding("utf-8");
// 设置文件上传最大值
sfu.setSizeMax(1024 * 1024 * 100);
// 读取存放目录
String fileDir = ROOT;
if (request.getParameter("fileDir") != null)
{
fileDir = request.getParameter("fileDir").toString();
}
try
{
// 从请求中解析文件列表
List<FileItem> files = sfu.parseRequest(request);
String directory = Directorys.localhost(fileDir);
FileUtils.validateAndMkdir(directory);
List<String> names = Lists.newArrayList();
for (FileItem file : files)
{
if (file.isFormField())
{
continue;
}
//中文名无法下载,所以改为其他
String fileName = file.getName();
Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
Matcher m = p.matcher(fileName);
if (m.find()) {
fileName=DateProvider.format()+ file.getName().substring(file.getName().lastIndexOf("."));
}
file.write(new File(directory + fileName));
names.add(fileDir + fileName);
}
rt.setResult(names);
}
catch (Exception e)
{
log.error("UploaderController.upload", e);
rt.setCode(GooidServerSay.CODE_ERROR);
rt.setMsg(MessageUtils.build(e));
}
return JSON.stringify(rt);
}
此代码存在一个问题,文件名如果设置为中文名称时,上传会失败,这个问题暂未解决,这里 我用的日期保存,如果有谁知道中文无法上传的问题怎么解决,可以下方评论,大家一起交流