jsp中上传图片(使用ajaxfileupload)
jsp中无刷新上传图片(前台使用jquery+ajaxfileupload),后台用commons-fileupload处理
需求:前台选择图片,页面显示上传后的图片地址
代码一:ajaxUploadImg.jsp
请百度搜索,并下载jQuery.js 及 ajaxfileupload.js
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
function ajaxFileUpload()
{
$("#loading")
.ajaxStart(function(){
$(this).show();
})//开始上传文件时显示一个图片
.ajaxComplete(function(){
$(this).hide();
});//文件上传完成将图片隐藏起来
$.ajaxFileUpload({
url:'FileUpload', //需要链接到服务器地址
secureuri:false,
fileElementId:'uploadFileInput', //文件选择框的id属性
dataType: 'json', //服务器返回的格式,可以是json
success: function (data, status) //相当于java中try语句块的用法
{
//alert(data); //data是从服务器返回来的值
$('#result').html('上传图片成功!请复制图片地址
'+data.src);
},
error: function (data, status, e) //相当于java中catch语句块的用法
{
$('#result').html('上传图片失败');
}
}
);
}
代码二: FileUpload.java
这里使用了commons-fileupload-1.2.1.jar的包,可以自行搜索下载
如果使用myeclipse,可以直接在Struts 2 Core Libraies中找到.
commons-fileupload-1.2.1.jar
package com.lz.servlet;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;
public class FileUpload extends HttpServlet {
public FileUpload() {
super();
}
public void destroy() {
super.destroy();
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
String realDir = request.getSession().getServletContext().getRealPath("");
String contextpath = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ contextpath + "/";
try {
String filePath = "uploadfiles";
String realPath = realDir+"\\"+filePath;
//判断路径是否存在,不存在则创建
File dir = new File(realPath);
if(!dir.isDirectory())
dir.mkdir();
if(ServletFileUpload.isMultipartContent(request)){
DiskFileItemFactory dff = new DiskFileItemFactory();
dff.setRepository(dir);
dff.setSizeThreshold(1024000);
ServletFileUpload sfu = new ServletFileUpload(dff);
FileItemIterator fii = null;
fii = sfu.getItemIterator(request);
String title = ""; //图片标题
String url = ""; //图片地址
String fileName = "";
String state="SUCCESS";
String realFileName="";
while(fii.hasNext()){
FileItemStream fis = fii.next();
try{
if(!fis.isFormField() && fis.getName().length()>0){
fileName = fis.getName();
Pattern reg=Pattern.compile("[.]jpg|png|jpeg|gif$");
Matcher matcher=reg.matcher(fileName);
if(!matcher.find()) {
state = "文件类型不允许!";
break;
}
realFileName = new Date().getTime()+fileName.substring(fileName.lastIndexOf("."),fileName.length());
url = realPath+"\\"+realFileName;
BufferedInputStream in = new BufferedInputStream(fis.openStream());//获得文件输入流
FileOutputStream a = new FileOutputStream(new File(url));
BufferedOutputStream output = new BufferedOutputStream(a);
Streams.copy(in, output, true);//开始把文件写到你指定的上传文件夹
}else{
String fname = fis.getFieldName();
if(fname.indexOf("pictitle")!=-1){
BufferedInputStream in = new BufferedInputStream(fis.openStream());
byte c [] = new byte[10];
int n = 0;
while((n=in.read(c))!=-1){
title = new String(c,0,n);
break;
}
}
}
}catch(Exception e){
e.printStackTrace();
}
}
response.setStatus(200);
String retxt ="{src:'"+basePath+filePath+"/"+realFileName+"',status:success}";
response.getWriter().print(retxt);
}
}catch(Exception ee) {
ee.printStackTrace();
}
}
public void init() throws ServletException {
// Put your code here
}
}
代码三: web.xml做如下
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
index.jsp
FileUpload
com.lz.servlet.FileUpload
FileUpload
/FileUpload