jsp中上传图片(使用ajaxfileupload)

5 篇文章 0 订阅
jsp中无刷新上传图片(前台使用jquery+ajaxfileupload),后台用commons-fileupload处理


需求:前台选择图片,页面显示上传后的图片地址


代码一:ajaxUploadImg.jsp

请百度搜索,并下载jquery.js 及 ajaxfileupload.js

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://"
			+ request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
	<script language="javascript" src="<%=basePath%>js/jquery.js" ></script>
	<script language="javascript" src="<%=basePath%>js/ajaxfileupload.js" > </script> 
	<script language="javascript" type="text/javascript" src="<%=basePath%>js/ezeditor.js"></script>
	<script type="text/javascript">
	function ajaxFileUpload()
	{
	
	$("#loading")
        .ajaxStart(function(){
            $(this).show();
        })//开始上传文件时显示一个图片
        .ajaxComplete(function(){
            $(this).hide();
        });//文件上传完成将图片隐藏起来
        
       $.ajaxFileUpload({
                 url:'<%=basePath %>FileUpload',             //需要链接到服务器地址
                 secureuri:false,
                 fileElementId:'uploadFileInput',                         //文件选择框的id属性
                 dataType: 'json',                                     //服务器返回的格式,可以是json
                 success: function (data, status)             //相当于java中try语句块的用法
                 {   
                 //alert(data);       //data是从服务器返回来的值   
                     $('#result').html('上传图片成功!请复制图片地址<br/>'+data.src);
 
                 },
                 error: function (data, status, e)             //相当于java中catch语句块的用法
                 {
                     $('#result').html('上传图片失败');
                 }
               }
             );
    }
	</script>
  </head>
  
  <body> 
  <div id="result" style="FONT:12px 宋体"></div><br/>
 <img id="loading" src="loading.gif" style="display:none;">
		<form name="form_uploadImg" action="" method="POST" enctype="multipart/form-data">
 <input id="uploadFileInput" type="file" size="45" name="uploadFileInput" class="input" />
 <input type="button" id="buttonUpload" οnclick="return ajaxFileUpload();" value="上传图片"/>
 </form>
</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做如下

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" 
	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">
  <display-name></display-name>	
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>

  <servlet>
    <servlet-name>FileUpload</servlet-name>
    <servlet-class>com.lz.servlet.FileUpload</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>FileUpload</servlet-name>
    <url-pattern>/FileUpload</url-pattern>
  </servlet-mapping>
</web-app>



  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值