在Web应用系统开发中,文件上传和下载功能是非常常用的功能,今天来讲一下JavaWeb中的文件上传的简单实现.
官网 (不知道为何翻墙也访问不了)
http://download.csdn.net/detail/dengchenlu/3957758 (CSDN下载页)
首先需要在页面里引入jquery.js和ajaxupload.js
<script src="jquery-1.9.min.js" type="text/javascript"></script>
<script src="ajaxupload3.9.js" type="text/javascript"></script>
然后创建一个需要绑定上传事件的div
<div id="btn" style="width:200px;height:100px;">点这里</div>
在js中初始化AjaxUpload对象
首先我们先来看下源码里的注释
window.AjaxUpload = function (button, options) {
this._settings = {
// Location of the server-side upload script
action: 'upload.php',
// File upload name
name: 'userfile',
// Additional data to send
data: {},
// Submit file as soon as it's selected
autoSubmit: true,
// The type of data that you're expecting back from the server.
// html and xml are detected automatically.
// Only useful when you are using json data as a response.
// Set to "json" in that case.
responseType: false,
// Class applied to button when mouse is hovered
hoverClass: 'hover',
// Class applied to button when AU is disabled
disabledClass: 'disabled',
// When user selects a file, useful with autoSubmit disabled
// You can return false to cancel upload
onChange: function (file, extension) {
},
// Callback to fire before file is uploaded
// You can return false to cancel upload
onSubmit: function (file, extension) {
},
// Fired when file upload is completed
// WARNING! DO NOT USE "FALSE" STRING AS A RESPONSE!
onComplete: function (file, response) {
}
};
上面的每个参数的注释都很简单易懂,这里我贴出一个实际的demo
function () {
var options = {
action: prefix+'/upload-img', //your url
responseType: 'json',
name: 'files',
onSubmit: function (file, extension) {
//do sth on submit
},
onComplete: function (file, uploadResult) {
//do sth on complete
},
onChange: function (file, extension) {
//do sth on change
}
};
new AjaxUpload($("#btn"), options);
}
这样就完成了的一个简单的初始化,下面我们来看下服务器端如何来接受,这里使用到的是java
@ResponseBody
@RequestMapping(value = "/upload-img", method = RequestMethod.POST, produces = MediaType.TEXT_HTML_VALUE)
public String upload(FileUploadForm fileUploadForm) throws IOException {
//根据接收到的FileUploadForm对象做一些处理
List<MultipartFile> files = fileUploadForm.getFiles();
return "balabala";
}
下篇预告 : Spring全局异常处理
网友评论