html5里使用ajax提交含有上传文件的form表单
来源:互联网 发布:matlab数学建模算法 编辑:程序博客网 时间:2024/05/16 07:43
这里会用到html5里的formdata类。
需要添加的js.css:
<link rel="stylesheet" type="text/css"
href="${pageContext.request.contextPath}/js/jquery-easyui-1.4/themes/default/easyui.css" />
<script type="text/javascript"
src="${pageContext.request.contextPath}/js/easyUI/jquery.easyui.min.js"></script>
触发按钮:
<div class="col-sm-12 padding_bottom_20 padding_top_20">
<a href="javascript:void(0)" id="updatefileButton" style="cursor:pointer " class="text_red">如果上述上传附件不能正常使用,可点击此处上传</a><br />
<div style="float:left;display:inline;" id="tip1"></div>
</div>
<!--文件上传弹窗-->
<div id="updateFile" class="easyui-window" modal="true" closed="true"
title=" 上传" iconCls="icon-save"
style="width:500px;height:240px;padding:5px;background-color:#fafafa;top:1900px;">
<div class="easyui-layout" fit="true">
<div region="center" border="false"
style="padding:10px;background:#fff;border:1px solid #ccc;">
<form id="uploadForm">
<input type="hidden" name="attid" id="attid" value="${attid }" />
<input type="hidden" name="uploadType" id="uploadType" value="4" />
选择附件:<br /><br /><input type="file" name="uploadFile"/><br/>
</form>
</div>
<div region="south" border="false"
style="text-align:right;height:30px;line-height:30px;">
<input class="easyui-linkbutton" type="button" id="nesup" onclick="updatefileload('${attid}','4')" value="上传"/>
<a class="easyui-linkbutton" iconCls="icon-cancel"
href="javascript:void(0)" onClick="$('#updateFile').window('close');">关闭</a>
</div>
</div>
</div>
<script>
$(function() {
$("#updatefileButton").click(function() {
$('#updateFile').window('open');
});
});
function updatefileload(attid,uploadType) {
var formfile=new FormData(document.getElementById("uploadForm"));
//var formfile=new FormData();
//formfile.append('uploadFile', $('input[name=uploadFile]')[0].files[0]);
//formfile.append('attid',$("#attid").val());
//formfile.append('uploadType',"4");
//var attid=$("#attid").val();
$.ajax({
url: '<c:url value="/fileserver/upload"/>',
//url: '<c:url value="/fileserver/upload?attid=${attid}&uploadType=4"/>',
type: 'POST',
data: formfile,
//data: formData,
//async: false,
cache: false,
contentType: false, //必须的
processData: false, //必须的
//dataType:"json", //不指定返回类型
success: function (data) {
if(JSON.parse(data).flag == "true"){
var mess="<font color=\"red\" size=\"2\">"+JSON.parse(data).url+"</font>";
$("#tip1").html(mess);
ymPrompt.alert("上传成功!" + JSON.parse(data).message,300,185,"信息提示",function(datas) {
if (datas == "ok") {
$('#updateFile').window('close');
}else{
$('#updateFile').window('close');
}
});
}else{
ymPrompt.alert("上传失败!" + "请重新上传",300,185,"信息提示",function(datas) {
if (datas == "ok") {
$('#updateFile').window('close');
}else{$('#updateFile').window('close');}
});
}
},
error : function(xhr, errorType, error, msg) {
hideLoading();
},
beforeSend : function() {
showLoading();
},
complete : function() {
hideLoading();
},
timeout : 60000 * 2
});
}
</script>
后端处理代码:
package servlet;
import java.io.File;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.UUID;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.web.context.WebApplicationContext;
import cn.nsl.domain.glob.ReportInfo;
import cn.nsl.web.Application;
import cn.nsl.web.util.WebUtils;
import com.jbetter.spring.orm.ICommonDao;
public class UploadServlet extends HttpServlet {
private static String CX="kjcxwt";
private static String YW="ywjswt";
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
private String imgSuffix="*.jpg;*.jpeg;*.png;*.gif;*.bmp;*.JPG;*.JPEG;*.PNG;*.GIF;*.BMP;";
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
boolean success=true;
Properties p=WebUtils.getProperties("/system.properties");
String savePath =p.getProperty("savePath");//this.getServletConfig().getServletContext().getRealPath("");
String urlPath=p.getProperty("urlPath");
String uploadType=request.getParameter("uploadType");
String attid=request.getParameter("attid");
String filename="";
savePath+=attid+"/";
File f1 = new File(savePath);
if (!f1.exists()) {
f1.mkdirs();
}
if (!f1.getParentFile().exists()) {
f1.getParentFile().mkdirs();
}
DiskFileItemFactory fac = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(fac);
upload.setHeaderEncoding("utf-8");
List<FileItem> fileList = null;
try {
fileList = upload.parseRequest(request);
} catch (FileUploadException ex) {
return;
}
Iterator<FileItem> it = fileList.iterator();
String name = "",originalName="";
String extName = "";
while (it.hasNext()) {
FileItem item = it.next();
if (item.isFormField()){
if(item.getFieldName().equals("attid")){ //获得表单信息中的非文件的属性值
System.out.println("上传信息中获得的attid:"+item.getString());
attid = item.getString();
}
if (item.getFieldName().equals("uploadType")){
System.out.println("上传信息中获得的uploadType:"+item.getString());
uploadType = item.getString();
}
}else{
name = item.getName();
originalName=name.substring(0,name.lastIndexOf("."));
long size = item.getSize();
String type = item.getContentType();
if (name == null || name.trim().equals("")) {
continue;
}
//扩展名格式:
if (name.lastIndexOf(".") >= 0) {
extName = name.substring(name.lastIndexOf("."));
}
File file = null;
do {
//生成文件名:
name = UUID.randomUUID().toString();
filename=name+extName;//访问url
file = new File(savePath + name + extName);
} while (file.exists());
File saveFile = new File(savePath + name + extName);
try {
item.write(saveFile);
} catch (Exception e) {
e.printStackTrace();
}
}
}
urlPath+=attid+"/"+filename;
WebApplicationContext webctx=Application.WebApp_CONTEXT;
ICommonDao dao=(ICommonDao) webctx.getBean("commonDAOProxy");
ReportInfo rinfo = new ReportInfo();
rinfo.setAttach_title(originalName);
rinfo.setAttach_filename(filename);
rinfo.setAttach_url(savePath+filename);
rinfo.setLocalurl(urlPath);
rinfo.setAttach_uploadtime(new Timestamp(new Date().getTime()));
rinfo.setAttid(attid);
if(WebUtils.isNotNull(request.getParameter("uploadDescribe"))){
rinfo.setDescribes(request.getParameter("uploadDescribe"));
}
if("5".equals(uploadType)){
rinfo.setAttach_type(YW);
}else if("6".equals(uploadType)){
rinfo.setAttach_type(YW);
}else{
rinfo.setAttach_type(CX);
}
rinfo.setFileType(Integer.valueOf(uploadType));
dao.save(rinfo);
String html = "{\"flag\":\"" + String.valueOf(success)
+ "\",\"message\":\"" + "已操作成功" + "\",\"url\":\""
+ urlPath + "\",\"id\":\""
+ rinfo.getId()+"\"}";
response.setCharacterEncoding("UTF-8");
response.getWriter().write(html);
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
}
web.xml的配置:
需要在web.xml里配置servlet参数
<servlet>
<description>FileServlet</description>
<display-name>FileServlet</display-name>
<servlet-name>FileServlet</servlet-name>
<servlet-class>servlet.UploadServlet</servlet-class>/***后台处理程序***/
</servlet>
<servlet-mapping>
<servlet-name>FileServlet</servlet-name>
<url-pattern>/fileserver/upload</url-pattern>/***前台url使用的路径***/
</servlet-mapping>
- html5里使用ajax提交含有上传文件的form表单
- 用jquery.form.js 实现ajax提交含有上传文件和普通字段的表单
- 使用ajax提交form表单,包括ajax文件上传
- 使用ajax提交form表单,包括ajax文件上传
- 使用ajax提交form表单,包括ajax文件上传
- 使用ajax提交form表单,包括ajax文件上传
- 使用ajax提交form表单,包括ajax文件上传
- 使用ajax提交form表单,包括ajax文件上传
- 使用ajax提交form表单,包括ajax文件上传
- 使用ajax提交form表单,包括ajax文件上传
- 使用ajax提交form表单,包括ajax文件上传
- 使用ajax提交form表单,包括ajax文件上传,转载
- 使用ajax提交form表单,包括ajax文件上传
- 使用ajax提交form表单,包括ajax文件上传
- 使用ajax提交form表单,包括ajax文件上传
- Ajax提交form表单,Ajax文件上传
- 使用ajax提交form表单,包括ajax文件上传的两种方式
- ajax异步提交含有文件的表单
- Linux命令分析: cat
- Java基础面试
- JNA实战笔记汇总<一> 简单认识JNA|成功调用JNA
- JDK源码包结构分类
- 分享:六个绝佳的PHP模板引擎
- html5里使用ajax提交含有上传文件的form表单
- 将已经赋过值的数组置为空
- 嵌套函数的工作原理
- Android——引用字体文件
- 直播类APP的弹幕效果
- Andrew Ng 深度学习课程小记
- 使用JavaScript将表格中的内容获取为二维数组
- MySQL--- DDL、DML、DCL都包括那些语句?
- 176. Second Highest Salary