jsp页面:
<form id="uploadWiasNews" enctype="multipart/form-data" method="post">
中文标题: <input type="text" name="titleNameCn" value='新闻1'/>
英文标题: <input type="text" name="titleNameEn" value='new1'/>
选择文件:<input data-role="none" type="file" name="file" width="120px">
<button data-role="none" onclick="uploadWiasNews();">上传</button>
</form>
<input id="input" type="hidden" value='${ctx}'>
js:
function uploadWiasNews(){
var form = new FormData(document.getElementById("uploadWiasNews"));
var localhostPaht=$("#input").val();
var url = localhostPaht + "/information/uploadWiasNews/uploadWiasNews.do"; //这里的“项目访问路径”要改为你自己的路径
$.ajax({
url : url,
data : form,
type : 'post',
processData:false,
contentType:false,
success : function(data){
alert("成功");
},
error : function(data){
}
});
}
controller:
@RequestMapping("/information/uploadWiasNews/uploadWiasNews.do")
public void uploadWiasNews(HttpServletRequest request, HttpServletResponse response) {
String titleCn = request.getParameter("titleNameCn");
String titleEn = request.getParameter("titleNameEn");
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
List<MultipartFile> fileList = multipartRequest.getFiles("file");
String path = request.getSession().getServletContext().getRealPath("/assets/static/news");
int t = 0;
int x = 0;
String notTypeError = "";
for(int i = 0; i < fileList.size(); i++) {
MultipartFile file = fileList.get(i);
String fileName = file.getOriginalFilename();
if(fileName.indexOf(".htm") > -1 || fileName.indexOf(".html") > -1) {
Map<String, Object> paramsMap = new HashMap<String, Object>();
paramsMap.put("titleCn", titleCn);
paramsMap.put("titleEn", titleEn);
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
paramsMap.put("fileName", "news_" + df.format(new Date()) + "." + fileName.split("\\.")[1]);
paramsMap.put("userName", AppFrameworkUtil.getUserName(request));
File dirFile = new File(path, paramsMap.get("fileName").toString());
//System.out.println("dir.exists()>>"+dirFile.exists());
try {
if(!dirFile.exists()){
dirFile.createNewFile();
}
//System.out.println("dir.exists()>>"+dirFile.exists());
// MultipartFile自带的解析方法
//file.get(i).transferTo(dirFile);
} catch (IOException e) {
e.printStackTrace();
}
InputStream input = null;
FileOutputStream output = null;
try {
input = file.getInputStream();
output = new FileOutputStream(dirFile);
byte[] bt = new byte[1024*1024];
int len = 0;
while((len = input.read(bt)) != -1) {
output.write(bt, 0, len);
}
input.close();
output.flush();
output.close();
uploadWiasNewsManager.uploadWiasNews(request, paramsMap);
t++;
} catch (IOException e) {
e.printStackTrace();
}
} else {
x++;
notTypeError = x + "条不是htm或html文件,导入失败!";
}
}
Map<String, Object> resultMap = new HashMap<String, Object>();
resultMap.put("data", t + "条导入成功, " + (fileList.size() - t) + "条导入失败!" + notTypeError);
ChartsUtil.renderJSON(response, AppFrameworkUtil.structureConfigParamsGroupJSONData(resultMap));
}
网友评论