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

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. SHOWMODALDIALOG表单提交时禁止打开新窗口

    前提条件:showmodaldialog中有表单form.当action="#"的时候,提交表单,不会打开新窗口,但这种#自提有时不能用,#是本页面完整的带参数的url,如果表单中 ...

  2. 洛谷 [P2485] 计算器

    快速幂+同余方程+BSGS 同余方程在解的时候要注意,在将exgcd求出的解变换为原方程的解的时候,要取模 BSGS的原理就是用分块+hash优化暴力,要注意特判 a 和 b 是 p 的倍数的时候. ...

  3. 【BZOJ3611】大工程(虚树,DFS序,树形DP)

    题意:有一棵树,树有边权,有若干次询问,给出一些点,求: 1.这些点互相之间的距离之和 2.点对距离中的最大和最小值 n<=1000000 q<=50000并且保证所有k之和<=2* ...

  4. net8:简易的文件磁盘管理操作二(包括文件以及文件夹的编辑创建删除移动拷贝重命名等)

    原文发布时间为:2008-08-07 -- 来源于本人的百度文章 [由搬家工具导入] using System;using System.Data;using System.Configuration ...

  5. Mysql安装及自动化部署脚本方案

    一.简介 数据库(Database)是按照数据结构来组织.存储和管理数据的仓库, 每个数据库都有一个或多个不同的API用于创建,访问,管理,搜索和复制所保存的数据. 我们也可以将数据存储在文件中,但是 ...

  6. eclipse 安卓虚拟机安装apk 及常见问题

    首先必须启动虚拟机然后如图操作:

  7. Codeforces 86D Powerful array (莫队算法)

    题目链接 Powerful array 给你n个数,m次询问,Ks为区间内s的数目,求区间[L,R]之间所有Ks*Ks*s的和. $1<=n,m<=200000,   1<=s< ...

  8. oracle学习笔记(十四) 数据库对象 索引 视图 序列 同义词

    数据库对象 用户模式:指数据库用户所创建和存储数据对象的统称.在访问其它用户模式的数据库对象时需加上用户模式. 如:scott.emp, scott.dept等. 数据库对象包括:表.视图.索引.序列 ...

  9. LightOJ1234 Harmonic Number 调和级数求和

    [题目] [预备知识] ,其中r是欧拉常数,const double r= 0.57721566490153286060651209; 这个等式在n很大 的时候 比较精确. [解法]可以在 n较小的时 ...

  10. GRYZY #13. 拼不出的数

    拼不出的数 lost.in/.out/.cpp [问题描述] 3 个元素的集合 {5, 1, 2} 的所有子集的和分别是 0, 1, 2, 3, 5, 6, 7, 8.发 现最小的不能由该集合子集拼出 ...