我以演示上传图片为例子:

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 提交所有表单内容及上传图片(文件),以及单独上传某个图片(文件)的更多相关文章

  1. 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 ...

  2. ajax提交form表单资料详细汇总

    一.ajax提交form表单和不同的form表单的提交主要区别在于,ajax提交表单是异步提交的,而普通的是同步提交的表单.通过在后台与服务器进行少量数据交换,ajax 可以使网页实现异步更新.这意味 ...

  3. Ajax提交from表单

    一,使用Ajax提交form表单到后台传参问题 1,首先,定义一个form: <form class="form-horizontal" role="form&qu ...

  4. ajax提交form表单

    1. ajax提交form表单和不同的form表单的提交主要区别在于,ajax提交表单是异步提交的,而普通的是同步提交的表单. 2. from视图部分 <form id="loginF ...

  5. jquery实现ajax提交form表单的方法总结

    本篇文章主要是对jquery实现ajax提交form表单的方法进行了总结介绍,需要的朋友可以过来参考下,希望对大家有所帮助 方法一:  function AddHandlingFeeToRefund( ...

  6. jquery的ajax提交form表单方式总结

    方法一: function AddHandlingFeeToRefund() { var AjaxURL= "../OrderManagement/AjaxModifyOrderServic ...

  7. Ajax提交Form表单的一种方法

    待提交的表单 <form id="updatePublicKey" enctype="multipart/form-data"> <div c ...

  8. ajax提交form表单问题

    form表单提交数据可以省下大量大量获取元素的代码,局部刷新时也可以用ajax提交form表单,但是要先把表单序列化,再把后台javaBean对象序列化,但是你有可能前后台都执行了系列化,但是后台还是 ...

  9. 使用ajax提交form表单,包括ajax文件上传【转载】

    [使用ajax提交form表单,包括ajax文件上传] 前言 转载:作者:https://www.cnblogs.com/zhuxiaojie/p/4783939.html 使用ajax请求数据,很多 ...

随机推荐

  1. BZOJ 1778 [Usaco2010 Hol]Dotp 驱逐猪猡 ——期望DP

    思路和BZOJ 博物馆很像. 同样是高斯消元 #include <map> #include <ctime> #include <cmath> #include & ...

  2. noip2017爆炸记——题解&总结&反省(普及组+提高组)

    相关链接: noip2018总结 noip2017是我见过的有史以来最坑爹的一场考试了. 今年北京市考点有一个是我们学校,我还恰好被分到了自己学校(还是自己天天上课的那个教室),于是我同时报了普及提高 ...

  3. chef cookbook 实战

    在Workstation中创建cookbook,并且上传到Chef server,以及其他与Chef相关的工作. 安装chef client命令 knife bootstrap 10.6.1.207 ...

  4. Powerdesigner 使用小技巧

    1.table与table之间:改直角为直线; 2.Name 和code 不联动

  5. android实现通知栏消息

    一.原理 消息推送有两种,一种是客户端定时直接到服务器搜索消息,如果发现有新的消息,就获取消息下来:另一种是服务器向客户端发送消息,也就是当有信息消息时,服务器端就会向客户端发送消息. 二.步骤(代码 ...

  6. Can't connect to X11 window server using 'localhost:0.0' 的解决

    Can't connect to X11 window server using 'localhost:0.0' 的解决 http://lufei-99999.blog.163.com/blog/st ...

  7. 迈出从3K到1W的重要一步——掌握设计模式

    IT职场的小菜经常有这样的疑问: 为什么一个相似的功能,大牛一会儿就搞定,然后悠闲地品着下午茶逛淘宝:而自己加班加点搞到天亮还做不完. 为什么用户提出需求变更后,大牛只需潇洒地敲敲键盘,改改配置:而自 ...

  8. uibutton去掉点击后背景有阴影的方法

    1,将normal和highlight两种方式都设置上图片即可 UIButton *goback = [[UIButton alloc]initWithFrame:CGRectMake(5.0f, 5 ...

  9. 391. Perfect Rectangle

    最后更新 一刷 16-Jan-2017 这个题我甚至不知道该怎么总结. 难就难在从这个题抽象出一种解法,看了别人的答案和思路= =然而没有归类总结到某种类型,这题相当于背了个题... 简单的说,除了最 ...

  10. BUPT复试专题—Python List(2014)

    题目描述 在Python中,List (列表)是一种非常重要的数据结构.它与C/C++/Java中的 数组有些类似,但支持添加新元素时的动态扩展.在这个问题中,你需要处理如下 的几种对List的操作. ...