ajax 提交所有表单内容及上传图片(文件),以及单独上传某个图片(文件)
我以演示上传图片为例子:
java代码如下(前端童鞋可以直接跳过看下面的html及js):
package com.vatuu.web.action; import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List; import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import net.sf.json.JSONObject; import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload; /**
* Servlet implementation class NewsUploadImage
* 上传新闻配图
*/
@WebServlet("/NewsUploadImage")
public class NewsUploadImage extends HttpServlet {
private static final long serialVersionUID = 1L; //上传配置
private static final int MEMORY_THRESHOLD = 1024 * 1024 ; // 1MB
private static final int MAX_FILE_SIZE = 1024* 200 ; // 200k
private static final int MAX_REQUEST_SIZE = 1024 * 1024 ; // 1MB
/**
* @see HttpServlet#HttpServlet()
*/
public NewsUploadImage() {
super();
// TODO Auto-generated constructor stub
} /**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doPost(request, response);
} /**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
// 检测是否为多媒体上传
if (!ServletFileUpload.isMultipartContent(request)) {
// 如果不是则停止
PrintWriter writer = response.getWriter();
writer.println("Error: 表单必须包含 enctype=multipart/form-data");
writer.flush();
return;
} // 配置上传参数
DiskFileItemFactory factory = new DiskFileItemFactory();
// 设置内存临界值 - 超过后将产生临时文件并存储于临时目录中
factory.setSizeThreshold(MEMORY_THRESHOLD);
// 设置临时存储目录
factory.setRepository(new File(System.getProperty("java.io.tmpdir"))); ServletFileUpload upload = new ServletFileUpload(factory); // 设置最大文件上传值
upload.setFileSizeMax(MAX_FILE_SIZE); // 设置最大请求值 (包含文件和表单数据)
upload.setSizeMax(MAX_REQUEST_SIZE); // 中文处理
upload.setHeaderEncoding("UTF-8"); // 这个路径相对当前应用的目录
String uploadPath = request.getServletContext().getRealPath("/download/news/images"); // 如果目录不存在则创建
File uploadDir = new File(uploadPath);
if (!uploadDir.exists()) {
uploadDir.mkdir();
} PrintWriter pw = response.getWriter();
JSONObject jsonObject = new JSONObject();
try {
// 解析请求的内容提取文件数据
@SuppressWarnings("unchecked")
List<FileItem> formItems = upload.parseRequest(request); if (formItems != null && formItems.size() > 0) {
// 迭代表单数据
for (FileItem item : formItems) {
// 处理不在表单中的字段
if (!item.isFormField()) {
String fileName = new File(item.getName()).getName();
//获取文件后缀名
String prefix=fileName.substring(fileName.lastIndexOf(".")+1);
//判断文件类型
if(prefix.equals("jpg") || prefix.equals("gif") || prefix.equals("png") || prefix.equals("jpeg")){
//以时间戳+pt两字命名文件
long currentTime=System.currentTimeMillis();
String filePath = uploadPath + currentTime+"pt."+prefix;
File storeFile = new File(filePath);
// 在控制台输出文件的上传路径
// 保存文件到硬盘
item.write(storeFile);
request.setAttribute("message",
"文件上传成功!");
jsonObject.put("fileName", currentTime+"pt."+prefix);
jsonObject.put("url", filePath); System.out.println("配图上传成功:" + filePath);
}else{
request.setAttribute("message",
"不支持该文件类型!");
jsonObject.put("url", "");
System.out.println("配图上传失败,不支持该文件类型!");
}
}
}
}
} catch (Exception ex) {
request.setAttribute("message",
"错误信息: " + ex.getMessage());
jsonObject.put("url", "");
} pw.print(jsonObject.toString());
pw.flush();
pw.close(); } }
一次提交所有表单的HTML如下,表单必须添加enctype属性,才能提交文件:
<form action="${basePath}vatuu/NewsAction?setAction=Add" method="post" name="newsForm" id="newsForm" enctype="multipart/form-data">
<table class="table_border table-form table-td-left table-th-normal">
<tr>
<th style="min-width: 150px; width: 20%">新闻标题</th>
<td><input type="text" id="newsTitle" name="newsTitle" class="input" style="width:40%"></td>
</tr> <tr id="newsContent1">
<th style="width: 20%">新闻内容</th>
<td style="width: 80%;" id="newsContent" name="newsContent"><script id="container" name="newsContent" type="text/plain" style="height: 700px; width: 99%;"></script></td>
</tr>
<tr id="newsUrl1" style="display: none">
<th>链接地址</th>
<td><input type="text" style="width: 40%;" id="newsUrl" name="newsUrl" value="http://" class="input" /></td>
</tr>
<tr>
<th style="width: 20%">新闻配图</th>
<td>
<input type="hidden" id="newsImgUrl" name="newsImgUrl" value="">
<input type="file" class="input" name="newsImage" id="newsImage"/>
<a href="javascript:uploadNewsImg()" class="btn btn-blue" >上传配图</a>
<img id="showUploadImg" width="80" height="50" style="display: none;" />
<span class="c-red" id="message" name="message"></span>
<span>提示:文件大小不超过200k,建议图片宽高为245px*160px</span>
</td>
</tr>
<tr>
<td colspan="2" style="text-align: center;">
<input type="submit" class="btn btn-blue" value="发布新闻 "/>
<input type="reset" class="btn btn-red" value="取消发布" >
</td>
</tr>
</table>
</form>
这里的提交可以直接summit 提交整个表单。
但是也有的时候需要单独上传图片或文件,回显是否上传成功,这里就需要用ajax进行处理。
首先引入jquery。
html跟上个差不多,唯一不同的是,不能给form 添加enctype=“multipart/form-data”属性,因为这里单独上传的时候没问题,但是提交整个表单的时候,若加上这个属性,
则整体提交表单的时候又会上传之前的文件,会出错,因此此处去掉enctype属性。
html如下:
<form action="${basePath}vatuu/NewsAction?setAction=Add" method="post" name="newsForm" id="newsForm" >
<table class="table_border table-form table-td-left table-th-normal">
<tr>
<th style="min-width: 150px; width: 20%">新闻标题</th>
<td><input type="text" id="newsTitle" name="newsTitle" class="input" style="width:40%"></td>
</tr> <tr id="newsContent1">
<th style="width: 20%">新闻内容</th>
<td style="width: 80%;" id="newsContent" name="newsContent"><script id="container" name="newsContent" type="text/plain" style="height: 700px; width: 99%;"></script></td>
</tr>
<tr id="newsUrl1" style="display: none">
<th>链接地址</th>
<td><input type="text" style="width: 40%;" id="newsUrl" name="newsUrl" value="http://" class="input" /></td>
</tr>
<tr>
<th style="width: 20%">新闻配图</th>
<td>
<input type="hidden" id="newsImgUrl" name="newsImgUrl" value="">
<input type="file" class="input" name="newsImage" id="newsImage"/>
<a href="javascript:uploadNewsImg()" class="btn btn-blue" >上传配图</a>
<img id="showUploadImg" width="80" height="50" style="display: none;" />
<span class="c-red" id="message" name="message"></span>
<span>提示:文件大小不超过200k,建议图片宽高为245px*160px</span>
</td>
</tr>
<tr>
<td colspan="2" style="text-align: center;">
<input type="submit" class="btn btn-blue" value="发布新闻 "/>
<input type="reset" class="btn btn-red" value="取消发布" >
</td>
</tr>
</table>
</form>
对应的ajax异步请求如下,需要使用jquery中的FormData提交文件(好像jquery必须高于1.2版本)。newsImage则是input type=“file”的id,此处我是上传的图片
//上传新闻配图
function uploadNewsImg(){
var formData = new FormData($( "#newsForm" )[0]);
formData.append("file",$("#newsImage")[0]);
formData.append("name",name);
$.ajax({
url:"../vatuu/NewsUploadImage",
type:"POST",
dataType:"json",
data:formData,
contentType: false,
processData: false,
success:function(data) {
if(data.url !="" && data.url != null){
$("#newsImgUrl").val(data.url);
var url = data.url;
//将上传的文件回显
$("#showUploadImg").css("display","block");
$("#showUploadImg").attr("src","../download/news/images/"+data.fileName);
$("#message").text("上传成功!");
}else{
$("#message").text("上传失败!请仔细检查您的图片类型和大小");
}
}
}); }
将返回的url 设置给之前隐藏的img标签,并把img 标签display: block ,这样就能判断图片是否成功了,最后再sumbit 整个表单就行了,
就可以返回的图片的url 提交给后台了。
ajax 提交所有表单内容及上传图片(文件),以及单独上传某个图片(文件)的更多相关文章
- Ajax提交form表单内容和文件(jQuery.form.js)
jQuery官网是这样介绍form.js A simple way to AJAX-ify any form on your page; with file upload and progress s ...
- ajax提交form表单资料详细汇总
一.ajax提交form表单和不同的form表单的提交主要区别在于,ajax提交表单是异步提交的,而普通的是同步提交的表单.通过在后台与服务器进行少量数据交换,ajax 可以使网页实现异步更新.这意味 ...
- Ajax提交from表单
一,使用Ajax提交form表单到后台传参问题 1,首先,定义一个form: <form class="form-horizontal" role="form&qu ...
- ajax提交form表单
1. ajax提交form表单和不同的form表单的提交主要区别在于,ajax提交表单是异步提交的,而普通的是同步提交的表单. 2. from视图部分 <form id="loginF ...
- jquery实现ajax提交form表单的方法总结
本篇文章主要是对jquery实现ajax提交form表单的方法进行了总结介绍,需要的朋友可以过来参考下,希望对大家有所帮助 方法一: function AddHandlingFeeToRefund( ...
- jquery的ajax提交form表单方式总结
方法一: function AddHandlingFeeToRefund() { var AjaxURL= "../OrderManagement/AjaxModifyOrderServic ...
- Ajax提交Form表单的一种方法
待提交的表单 <form id="updatePublicKey" enctype="multipart/form-data"> <div c ...
- ajax提交form表单问题
form表单提交数据可以省下大量大量获取元素的代码,局部刷新时也可以用ajax提交form表单,但是要先把表单序列化,再把后台javaBean对象序列化,但是你有可能前后台都执行了系列化,但是后台还是 ...
- 使用ajax提交form表单,包括ajax文件上传【转载】
[使用ajax提交form表单,包括ajax文件上传] 前言 转载:作者:https://www.cnblogs.com/zhuxiaojie/p/4783939.html 使用ajax请求数据,很多 ...
随机推荐
- BZOJ 2246 [SDOI2011]迷宫探险 ——动态规划
概率DP 记忆化搜索即可,垃圾数据,就是过不掉最后一组 只好打表 #include <cstdio> #include <cstring> #include <iostr ...
- HDU 4609 3-idiots ——FFT
[题目分析] 一堆小木棍,问取出三根能组成三角形的概率是多少. Kuangbin的博客中讲的很详细. 构造一个多项式 ai=i的个数. 然后卷积之后去重. 统计也需要去重. 挺麻烦的一道题. #inc ...
- 刷题总结——道路覆盖(ssoj)
题目: 题目描述 Tar 把一段凹凸不平的路分成了高度不同的 N 段(每一段相同高度),并用 H[i] 表示第 i 段高度.现在 Tar 一共有 n 种泥土可用,它们都能覆盖给定的连续的 k 个部分. ...
- ElasticSearch 索引查询使用指南——详细版
我们通常用用_cat API检测集群是否健康. 确保9200端口号可用: curl 'localhost:9200/_cat/health?v' 绿色表示一切正常, 黄色表示所有的数据可用但是部分副本 ...
- linux命令netstat或ifconfig未找到
linux命令netstat或ifconfig未找到 linux使用netstat或者ifconfig命令时,显示命令未找到.通过yum search netstat这个命令,匹配结果如下:===== ...
- Jetson TK1 四:重新安装系统(刷机)
转载:http://blog.sina.com.cn/s/blog_bab3fa030102vk21.html Jetson TK1是NVIDIA基于Tegra K1开发的一块低成本开发板,板载一块T ...
- 你还在为移动端选择器picker插件而捉急吗?
http://www.cnblogs.com/jingh/p/6381079.html 开题:得益于项目的上线,现在终于有时间来写一点点的东西,虽然很浅显,但是我感觉每经历一次项目,我就学到了很多的东 ...
- bootstrap -- col-sm-6 和 col-xs-6
- 深入理解javascript之设计模式
设计模式 设计模式是命名.抽象和识别对可重用的面向对象设计实用的的通用设计结构. 设计模式确定类和他们的实体.他们的角色和协作.还有他们的责任分配. 每个设计模式都聚焦于一个面向对象的设计难题或问题. ...
- BUPT复试专题—进程管理(2014网研)
题目描述 在操作系统中,进程管理是非常重要的工作.每个进程都有唯一的进程标识PID.每个进程都可以启动子进程,此时我们称该它本身是其子进程的父进程.除PID为0的进程之外,每个进程冇且只冇一个父进程. ...