ajax上传带文件的form表单,springmvc接收
2017-12-13 22:29
447 查看
数据都保存到HttpServletRequest中
@Override
public boolean insertBook(HttpServletRequest request) {
try{
//用于封装数据
Book book = new Book();
//解析请求中的数据
MultipartHttpServletRequest mpRequest = (MultipartHttpServletRequest) request;
String bookName = mpRequest.getParameter("bookName");
float price = Float.parseFloat(mpRequest.getParameter("price"));
Integer num = Integer.parseInt(mpRequest.getParameter("num"));
String date = mpRequest.getParameter("publishDate");
SimpleDateFormat format = new SimpleDateFormat("yyyy-mm-dd");
Date publishDate = format.parse(date);
//封装数据
book.setBookName(bookName);
book.setPrice(price);
book.setNum(num);
book.setPopular(0);
book.setPublishDate(publishDate);
MultipartFile file = mpRequest.getFile("imageUrl");
String path = request.getSession().getServletContext().getRealPath("bookImage");
String imageUrl = UploadUtil.uploadFile(file, path);
book.setImageUrl(imageUrl);
bookMapper.insertBook(book);
return true;
}catch(Exception e){
e.printStackTrace();
return false;
}
//return false;
}
解析存放图片的imageUrl
public static String uploadFile(MultipartFile file, String path) throws IOException{
//上传文件的真实名称
String name = file.getOriginalFilename();
//System.out.println(name);
//获取后缀名
String suffixName = name.substring(name.lastIndexOf("."));
//System.out.println(suffixName);
//自定义随机数
String hash = Integer.toHexString(new Random().nextInt());
String fileName = hash + suffixName;
//System.out.println(fileName);
File tempFile = new File(path, fileName);
if(!tempFile.getParentFile().exists()){
tempFile.getParentFile().mkdir();
}
if(tempFile.exists()){
tempFile.delete();
}
tempFile.createNewFile();
file.transferTo(tempFile);
return tempFile.getName();
}
参考文章:http://blog.csdn.net/wlphyl/article/details/51571402
相关文章推荐
- Spring利用MultipartFile接收FormData对象上传文件(可接收AJAX上传的包含多文件的复杂表单内容)
- 使用ajax提交form表单,包括ajax文件上传
- 使用ajax提交form表单,包括ajax文件上传
- 【原创】AJAX上传文件,formdata表单提交问题
- 使用ajax提交form表单,包括ajax文件上传
- ajax提交普通表单或者文件上传的form 带回调函数
- 使用ajax提交form表单,包括ajax文件上传 转http://www.cnblogs.com/zhuxiaojie/p/4783939.html
- 使用ajax提交form表单,包括ajax文件上传
- jQuery.form.js是一个form插件,支持ajax表单提交和ajax文件上传。
- js_ajax模拟form表单提交_多文件上传_支持单个删除
- ajax上传form表单或者文件以及结合validate验证
- 使用ajax提交form表单,包括ajax文件上传
- Ajax上传带有普通input和文件的表单Form
- SpringMVC前台利用ajax和FormData上传文件
- 使用ajax提交form表单,包括ajax文件上传
- form表单,AJAX上传文件
- 使用ajax提交form表单,包括ajax文件上传
- ajax上传文件,提交表单,使用FormData和XMLHttpRequest提交表单
- form表单文件上传 servlet文件接收
- 使用ajax提交form表单,包括ajax文件上传