首页 > 代码库 > JQuery 实现文件上传
JQuery 实现文件上传
简述:
实现前端使用jquery上传文件
后台用servlet处理文件上传以及保存
知识点:
1. 用到ajaxfileupload.js库
2. 后台servlet文件保存
其中ajaxfileupload的库下载地址:
http://www.phpletter.com/download_project_version.php?version_id=34
Maven中需要添加两个java的库,用来上传以及在服务器保存文件
[html] view plaincopy
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-io</artifactId>
<version>1.3.2</version>
</dependency>
项目结构(主要是js)
testUpload.html
[html] view plaincopy
<!DOCTYPE html>
<head>
<title>MyWebProject</title>
<meta charset="utf-8" />
<link type="text/css" href="./lib/css/jquery-ui-1.8.19.custom.css"
rel="stylesheet" />
<link type="text/css" href="./lib/css/ajaxfileupload.css"
rel="stylesheet" />
<script type="text/javascript" src="./lib/js/jquery-1.8.3.js"></script>
<script type="text/javascript" src="./lib/js/ajaxfileupload.js"></script>
<script type="text/javascript">
function ajaxFileUpload() {
$.ajaxFileUpload({
url : "./UploadFile", //submit to UploadFileServlet
secureuri : false,
fileElementId : ‘fileToUpload‘,
dataType : ‘text‘, //or json xml whatever you like~
success : function(data, status) {
$("#result").append(data);
},
error : function(data, status, e) {
$("#result").append(data);
}
});
return false;
}
</script>
</head>
<body>
<!-- upload file -->
<form name="form" action="./UploadFile" method="POST" enctype="multipart/form-data">
<table class="tableForm">
<thead>
<tr>
<th>JQuery Ajax File Upload</th>
</tr>
</thead>
<tbody>
<tr>
<td><input id="fileToUpload" type="file" size="45"
name="fileToUpload" class="input"></td>
</tr>
</tbody>
<tfoot>
<tr>
<td><button class="button" id="buttonUpload"
onclick="return ajaxFileUpload();">Upload</button></td>
</tr>
</tfoot>
</table>
<div id="result" style="margin-left:200px"></div>
</form>
</body>
</html>
后台实现:
参考:http://blog.163.com/lin305_gf/blog/static/969524402011718102116625/
UploadFileServlet.java
[java] view plaincopy
package mwp.servlet;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
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.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Servlet implementation class UploadFileServlet
*/
public class UploadFileServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static Logger logger = LoggerFactory.getLogger(UploadFileServlet.class);
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
//判断提交过来的表单是否为文件上传菜单
boolean isMultipart= ServletFileUpload.isMultipartContent(request);
if(isMultipart){
//构造一个文件上传处理对象
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
Iterator items;
try{
//解析表单中提交的所有文件内容
items = upload.parseRequest(request).iterator();
while(items.hasNext()){
FileItem item = (FileItem) items.next();
if(!item.isFormField()){
//取出上传文件的文件名称
String name = item.getName();
//取得上传文件以后的存储路径
String fileName = name.substring(name.lastIndexOf(‘\\‘) + 1, name.length());
//上传文件以后的存储路径
String saveDir = this.getServletContext().getRealPath("/upload/");
if (!(new File(saveDir).isDirectory())){
new File(saveDir).mkdir();
}
String path= saveDir + File.separatorChar + fileName;
//上传文件
File uploaderFile = new File(path);
item.write(uploaderFile);
}
}
}catch(Exception e){
e.printStackTrace();
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
}
response.setStatus(HttpServletResponse.SC_OK);
response.getWriter().append("Success Upload");
}
}
}
测试界面:
如若数据交换格式是JSON,则如下示例
JS
[javascript] view plaincopy
/**
* 上传图片
*/
function uploadUnitImage() {
showLoading("正在上传,请等待...");
$.ajaxFileUpload
(
{
url:‘/my-web/fileUpload?action=uploadImage‘,//用于文件上传的服务器端请求地址,目前与优惠券上传图片请求地址一致
secureuri:false,//一般设置为false
fileElementId: ‘unitImageToUpload‘, //文件上传空间的id属性
dataType: ‘json‘,//返回值类型 一般设置为json
success: function (data, status) //服务器成功响应处理函数
{
if(typeof(data.error) != ‘undefined‘)
{
if(data.error != ‘‘)
{
alert(data.error);
dismissLoading();
}else
{
//若上传成功则自定义一些事
// do something
}
}
},
error: function (data, status, e)//服务器响应失败处理函数
{
alert(e);
dismissLoading();
}
}
)
}
JAVA
[java] view plaincopy
public void uploadImage(
HttpServletRequest request,HttpServletResponse response) throws Exception{
logger.debug("上传图片");
//上传图片
String fileUrl=uploadFileAndGetFileUrl(request);
String responseText = "";
if(!StringUtils.isEmpty(fileUrl)){
logger.debug("图片下载地址是"+fileUrl);
responseText="{error: ‘‘,url: ‘"+fileUrl+"‘}";
}else{
logger.debug("账户创建页面,图片上传失败");
responseText="{error: ‘‘}";
}
responseOutWithText(response, responseText);
}
由于AjaxFileUpload在解析返回的response若为JSON数据时会出现问题,所以需要转为text
[java] view plaincopy
/**
* 以文本形式下发数据
* @param response
* @param responseText
*/
protected void responseOutWithText(HttpServletResponse response,
String responseText) {
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html");
PrintWriter out = null;
try {
out = response.getWriter();
out.println(responseText);
out.close();
logger.debug("下发的数据是");
logger.debug(responseText);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (out != null) {
out.close();
}
}
}
JQuery 实现文件上传