----------------------------------------------- 前端 ------------------------------------------
1. 先导入<script type="text/javascript" src="/js/ajaxfileupload.js"></script>
4. 相应的css代码
-------------------------------------- 服务端 ---------------------------------------------
1.
List<SortFile> sortFileArray = ImageUploadUtil.saveFile(request,paramConfig.getTempPath(), "cdn");
2.
/
**
*
* @param request
* @param tempPath (临时存放路径)
* @param fileSaveDirName (保存文件的目录名)
* @return fullFilePath (返回完整的文件路径)
* @throws Exception
*/
public static List<SortFile> saveFile(HttpServletRequest request,String tempPath,String fileSaveDirName) throws Exception {
List<SortFile> sortFileArray = new ArrayList<SortFile>();
String suffix = null;//后缀名
try{
if (!ServletFileUpload.isMultipartContent(request)) {
return null;
}
String fileSavePath = tempPath;
if(tempPath.indexOf("/",tempPath.length() - 1) >= 0) {
fileSavePath += fileSaveDirName;
} else {
fileSavePath += File.separator + fileSaveDirName;
}
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("UTF-8");
// 设置临时文件存储位置
File file = new File(tempPath);
// 设置内存缓冲区,超过后写入临时文件
factory.setSizeThreshold(10240);
// 创建文件夹
if(!file.exists()){
file.mkdirs();
}
factory.setRepository(file);
List<?> items = upload.parseRequest(request);
FileItem item = null;
for (int i = 0 ;i < items.size(); i++){
item = (FileItem) items.get(i);
if (!item.isFormField() && item.getName()!=null && item.getName().length()>0) {
File dir = new File(fileSavePath);
if(!dir.exists()){
dir.mkdirs();
}
suffix = getSuffix(item.getName());
String fullFilePath = fileSavePath+File.separator+DateUtil.ymdFormat(new Date())+UUID.randomUUID().toString()+"."+suffix;
// 保存文件
item.write(new File(fullFilePath));
SortFile sortFileInfo = new SortFile();
sortFileInfo.setFilePath(fullFilePath);
sortFileInfo.setFileName(item.getName());
sortFileInfo.setValue(item.getFieldName());
// 页面配置的上传文件名需要设置为 pic_0,pic_1... e.g. <input type="file" name="pic_0" />
String sortStr = item.getFieldName().replace("pic_","");
sortFileInfo.setSortNum(StringUtil.isEmpty(sortStr) ? 0 : (StringUtil.isNumeric(sortStr) ? Integer.parseInt(sortStr) : 0));
sortFileArray.add(sortFileInfo);
}
}
} catch(Exception e) {
log.error("saveFile 到临时目录报错: fileSaveDirName="+fileSaveDirName,e);
}
sort(sortFileArray);
return sortFileArray;
}
原文链接:/ajax/160635.html