html5 file upload and form data by ajax
html5 file upload and form data by ajax
最近接了一个小活,在短时间内实现一个活动报名页面,其中遇到了文件上传。
我预期的效果是一次ajax post请求,然后在后台java restlet的下面一次解决文件上传和form表单的处理。一次搞定问题。当然这是我的预期,真正实现起来还是不太顺利。
在网上很有很多文件上传的例子(尝试了uploadify,ajaxfileupload),可是很遗憾,在我这里好像都没有成功!
苦于自己的javascript水平太菜,也没有带多的精力来弄,
然后在google的帮助下 在这里,这里,这里的指引下,终于可以实现我要的效果.
ajax post => form + file (formdata) => restlet后台处理
下面具体说说代码部分。
html部分:
<html>
<header>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="//cdn.bootcss.com/jquery/1.11.3/jquery.min.js"></script>
</header>
<body>
<h1>*****Upload File with RESTFul WebService*****</h1>
<form id = "myform" >
<fieldset>
<legend>Upload File</legend>
<input type="file" id ="fileToUpload" name="fileToUpload"/><br />
<br /><br />
Party ID<input type="text" id = "partyid" name="partyid" /><br />
<a id="submit" href="javascript:void(0);" >提交</a>
</fieldset>
</form>
<script type="text/javascript">
$("#submit").click( function(){
var partyid = $("#partyid").val();
var fileToUpload = $("#fileToUpload").val();
var options = {
'event': 'xxxx2015',
'info': {
'partyid': partyid,
'fileToUpload': fileToUpload,
}
};
//file upload
console.log($("#myform").serialize())
console.log(fileToUpload)
console.log(partyid)
var formData = new FormData();
formData.append( 'fileToUpload', $( '#fileToUpload' )[0].files[0] );
formData.append( 'partyid', partyid);
$.ajax({
url: '../restful/v1.0/api/app/enroll/upload?token=JA1mqLiXDgcZ0ijJhE9R',
type: "POST",
contentType: false,
cache: false,
processData: false,
data: formData,
dataType: "json",
success: function (res) {
if (res.status) {
alert('注册成功!电子票已发送到你的手机/邮箱');
console.log(res);
} else {
switch (res.message) {
case 'hasApplied':
$('#user_info').text('');
alert('您已报名过此次大会,无需重复报名');
break;
default :
console.log(res.message);
alert('啊哦~图片提交失败,请重启提交');
break;
}
}
}, error: function (res) {
alert('啊哦~图片提交失败,请重启提交');
}
});
});
</script>
</body>
最主要是是ajax中这三行:
contentType: false,
cache: false,
processData: false,
后台代码部分 springmvc + restlet:
public class EnrollFileUploadResource extends ServerResourceBase{
private static Logger logger = Logger.getLogger(EnrollFileUploadResource.class.getName());
private EnrollRegisterService enrollRegisterService;
String parameter="";
@Override
protected void doInit() throws ResourceException {
logger.info("开始执行");
super.doInit();
}
@Post
public Representation createTransaction(Representation entity) {
Representation rep = null;
JSONObject json=new JSONObject();
if (entity != null) {
if (MediaType.MULTIPART_FORM_DATA.equals(entity.getMediaType(), true)) {
// 1/ Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(1000240);
// 2/ Create a new file upload handler
RestletFileUpload upload = new RestletFileUpload(factory);
List<FileItem> items;
try {
Request req = getRequest();
// 3/ Request is parsed by the handler which generates a list of FileItems
items = upload.parseRequest(req);
Map<String, String> props = new HashMap<String, String>();
File file = null;
String filename = null;
for (final Iterator<FileItem> it = items.iterator(); it.hasNext(); ) {
FileItem fi = it.next();
String name = fi.getName();
if (name == null) {
props.put(fi.getFieldName(), new String(fi.get(), "UTF-8"));
} else {
try {
String tempDir = getClass().getClassLoader().getResource("").getPath();
tempDir = tempDir.substring(0,tempDir.lastIndexOf("WEB-INF"));
String osName = System.getProperty("os.name");
if(osName.toLowerCase().indexOf("windows")>-1){
tempDir = tempDir.substring(1, tempDir.length());
}
String uploadingPath = tempDir + "static" + File.separatorChar +"uploading";
File f = new File(uploadingPath);
if (!f.exists()) {
f.mkdirs();
}
String time = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
String str=name.substring(name.lastIndexOf("."));
filename = time + RandomUtil.getStringCode(8)+str;
file = new File(uploadingPath+ File.separator+ filename);
fi.getInputStream();
fi.write(file);
props.put("image", filename);
} catch (Exception e) {
e.printStackTrace();
json.put("status", false);
json.put("message","fileUploadFail"); // 已经报过名了
}
}
}
// [...] my processing code
EnrollUser user =new EnrollUser();
user.setEvent(props.get("event"));
user.setUserName(props.get("userName"));
user.setMobile(props.get("mobile"));
。。。
user.setImage(props.get("image"));
user.setCreate_time(TimeUtil.getNowTimeByPattern(TimeUtil.DATE_DEFAULT_PATTERN));
if(enrollRegisterService.hasEnrolled(user))
{
json.put("status",false);
json.put("message","hasApplied"); // 已经报过名了
}
else
{
enrollRegisterService.saveOrUpdateData(user);
json.put("status",true);
json.put("info","成功");
}
} catch (Exception e) {
// The message of all thrown exception is sent back to
// client as simple plain text
getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
e.printStackTrace();
rep = new StringRepresentation(e.getMessage(), MediaType.TEXT_PLAIN);
}
} else {
// other format != multipart form data
getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
rep = new StringRepresentation("Multipart/form-data required", MediaType.TEXT_PLAIN);
}
} else {
// POST request with no entity.
getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
rep = new StringRepresentation("Error", MediaType.TEXT_PLAIN);
}
json.put("status",true);
return new StringRepresentation(json.toString());
}
public void setEnrollRegisterService(EnrollRegisterService enrollRegisterService) {
this.enrollRegisterService = enrollRegisterService;
}
}
完毕。
至于配置springmvc +restlet的配置环境如何,这里就不再说明。
如有问题,欢迎讨论。
html5 file upload and form data by ajax的更多相关文章
- 【转发】Html5 File Upload with Progress
Html5 File Upload with Progress Posted by Shiv Kumar on 25th September, 2010Senior Sof ...
- jQuery File Upload 单页面多实例的实现
jQuery File Upload 的 GitHub 地址:https://github.com/blueimp/jQuery-File-Upload 插件描述:jQuery File Upload ...
- jQuery File Upload blueimp with struts2 简单试用
Official Site的话随便搜索就可以去了 另外新版PHP似乎都有问题 虽然图片都可以上传 但是response报错 我下载的是8.8.7木有问题 但是8.8.7版本结合修改main. ...
- html5 file 上传文件
<body> <header> <h2>Pure HTML5 file upload</h2> </header> <div clas ...
- Web 前沿——HTML5 Form Data 对象的使用
XMLHttpRequest Level 2 添加了一个新的接口——FormData.利用 FormData 对象,我们可以通过 JavaScript 用一些键值对来模拟一系列表单控件,我们还可以使用 ...
- HTML5 Form Data 对象的使用
HTML5 Form Data 对象的使用 MDN: https://developer.mozilla.org/zh-CN/docs/Web/Guide/Using_FormData_Object ...
- [WebAPI] - 使用 Ajax 提交 HTML Form Data 到 WebAPI 的方法
背景 根据HTTP标准,HTTP请求可以使用多种请求方法. HTTP 1.0 定义了三种请求方法:GET.POST 和 HEAD 方法.HTTP 1.1 新增了五种请求方法:OPTIONS.PUT.D ...
- [整理]Ajax Post请求下的Form Data和Request Payload
Ajax Post请求下的Form Data和Request Payload 通常情况下,我们通过Post提交表单,以键值对的形式存储在请求体中.此时的reqeuest headers会有Conten ...
- AJAX POST请求中参数以form data和request payload形式在servlet中的获取方式
转载:http://blog.csdn.net/mhmyqn/article/details/25561535 HTTP请求中,如果是get请求,那么表单参数以name=value&name1 ...
随机推荐
- Android读取/dev/graphics/fb0 屏幕截图
Android屏幕截图有很多方式这里只使用其中一种截图 主要是读取/dev/graphics/fb0,进行转换,复杂点就在如何把读取的数据进行转换. 可以参考一下这篇文章:http://blog.ch ...
- Swift下自定义xib添加到Storyboard
猴子原创,欢迎转载.转载请注明: 转载自Cocos2Der-CSDN,谢谢! 原文地址: http://blog.csdn.net/cocos2der/article/details/51657154 ...
- C++ Primer 有感(顺序容器)
1.顺序容器的元素排列次序与元素的值无关,而是由元素添加到容器里的次序决定. 2. 顺序容器 vector 支持快速随机访问 list ...
- HTML DOCTYPE 的重要性
定义和用法 <!DOCTYPE> 声明必须是 HTML 文档的第一行,位于 <html> 标签之前. <!DOCTYPE> 声明不是 HTML 标签:它是指示 we ...
- Android Studio 从安装到配置使用
Android Studio是谷歌为android量身定制的IDE,在2013年谷歌大会上提出之后一直持续更新,现在已经是功能十分强劲的android开发工具,作为一个android开发者,还是早点转 ...
- 关于React Native 报Export declarations are not supported by current JavaScript version错误的解决问题
设置.js文件默认以jsx的语法打开 在没有进行设置的情况下,每次打开WebStorm的时候打开包含jsx语法的.js文件都会有以下提示: 当然我们点击转换后就可以了,但是每次都会提示,所以还是来一个 ...
- UML之结尾篇
作为十期的孩子,我们已经开发过两个系统,学生管理系统和机房收费系统,也接触了软工,编写了一系列文档,不知道小朋友有没有这种感觉,开发一个系统软件和编写一个程序是不一样的,他们之间的差别,用一个比喻来说 ...
- C语言设计模式-封装-继承-多态
快过年了,手头的工作慢慢也就少了,所以,研究技术的时间就多了很多时间,前些天在CSDN一博客看到有大牛在讨论C的设计模式,正好看到了,我也有兴趣转发,修改,研究一下. 记得读大学的时候,老师就告诉我们 ...
- Linux 内核配置机制(make menuconfig、Kconfig、makefile)讲解
前面我们介绍模块编程的时候介绍了驱动进入内核有两种方式:模块和直接编译进内核,并介绍了模块的一种编译方式--在一个独立的文件夹通过makefile配合内核源码路径完成 那么如何将驱动直接编译进内核呢? ...
- jdk8中tomcat修改配置PermSize为MetaspaceSize
JDK8中用metaspace代替permsize,因此在许多我们设置permsize大小的地方同样需要修改配置为metaspace 将-XX:PermSize=200m;-XX:MaxPermSiz ...