Uploadify v3.2.1 上传图片并预览

前端JSP:

<script type="text/javascript">

			$(function() {
			    $("#upload_org_code").uploadify({
			    	‘height‘        : 27,
			    	‘width‘         : 80,
			    	‘buttonText‘    : ‘选择图片‘,
			        ‘swf‘           : ‘${pageContext.request.contextPath}/js/uploadify/uploadify.swf‘,
			        ‘uploader‘      : ‘${pageContext.request.contextPath}/uploadIMGSerlet‘,
			        ‘auto‘          : true,
			        ‘multi‘         : false,
			        ‘removeCompleted‘:false,
			        ‘cancelImg‘     : ‘${pageContext.request.contextPath}/js/uploadify/uploadify-cancel.png‘,
			        ‘fileTypeExts‘  : ‘*.jpg;*.jpge;*.gif;*.png‘,
			        ‘fileSizeLimit‘ : ‘2MB‘,
			        ‘onUploadSuccess‘:function(file,data,response){
			        	$(‘#‘ + file.id).find(‘.data‘).html(‘‘);
			        	$("#upload_org_code_name").val(data);
			        	$("#upload_org_code_img").attr("src","${pageContext.request.contextPath}/getImg?file="+data);
			        	$("#upload_org_code_img").show();
			        },
			        //加上此句会重写onSelectError方法【需要重写的事件】
			      	‘overrideEvents‘: [‘onSelectError‘, ‘onDialogClose‘],
			        //返回一个错误,选择文件的时候触发
			        ‘onSelectError‘:function(file, errorCode, errorMsg){
			            switch(errorCode) {
			                case -110:
			                    alert("文件 ["+file.name+"] 大小超出系统限制的" + jQuery(‘#upload_org_code‘).uploadify(‘settings‘, ‘fileSizeLimit‘) + "大小!");
			                    break;
			                case -120:
			                    alert("文件 ["+file.name+"] 大小异常!");
			                    break;
			                case -130:
			                    alert("文件 ["+file.name+"] 类型不正确!");
			                    break;
			            }
			        },
			    });

</script>

  

            <tr>
                        <td align="right"><font style="color: red;">*</font>组织代码机构:</td>
                        <td>
                        	<table>
                        		<tr>
                        			<td width="45%"><input type="file" name="upload_org_code" id="upload_org_code"/></td>
                        			<td><img style="display: none" id="upload_org_code_img" src="" width="150" height="150"></td>
                        		</tr>
                        	</table>
	                        <input type="hidden" name="upload_org_code_name" id="upload_org_code_name" />
	                        <hr>
                        </td>
                    </tr>

  

后端servlet:

package com.mybank.enterprise.framework.servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;

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.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.mybank.enterprise.util.Constant;
import com.mybank.enterprise.util.StringUtil;

public class UploadIMGSerlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	// 上传文件的保存路径
	private String configPath = Constant.RB.getString("img_path");
	// 临时文件路径
	private String dirTemp = "resource/temp/";

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		String ret_fileName = null;//返回给前端已修改的图片名称

		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=UTF-8");
		PrintWriter out = response.getWriter();

		// 文件保存目录路径
		String savePath = configPath;

		// 临时文件目录
		String tempPath = this.getServletContext().getRealPath("/") + dirTemp;

		// 创建文件夹
		File dirFile = new File(savePath);
		if (!dirFile.exists()) {
			dirFile.mkdirs();
		}

		// 创建临时文件夹
		File dirTempFile = new File(tempPath);
		if (!dirTempFile.exists()) {
			dirTempFile.mkdirs();
		}

		DiskFileItemFactory factory = new DiskFileItemFactory();
		factory.setSizeThreshold(20 * 1024 * 1024); // 设定使用内存超过5M时,将产生临时文件并存储于临时目录中。
		factory.setRepository(new File(tempPath));  // 设定存储临时文件的目录。

		ServletFileUpload upload = new ServletFileUpload(factory);
		upload.setHeaderEncoding("UTF-8");

		try {
			List<?> items = upload.parseRequest(request);
			Iterator<?> itr = items.iterator();

			while (itr.hasNext()) {
				FileItem item   = (FileItem) itr.next();
				String fileName = item.getName();
				if(fileName!=null){
					String endstr = fileName.substring(fileName.indexOf("."),fileName.length());
					fileName      = StringUtil.createSerial20().concat(endstr);
					ret_fileName  = fileName;
				}
				if (!item.isFormField()) {

					try {
						File uploadedFile = new File(savePath,fileName);

						OutputStream os = new FileOutputStream(uploadedFile);
						InputStream is = item.getInputStream();
						byte buf[] = new byte[1024];// 可以修改 1024 以提高读取速度
						int length = 0;
						while ((length = is.read(buf)) > 0) {
							os.write(buf, 0, length);
						}
						// 关闭流
						os.flush();
						os.close();
						is.close();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}

		} catch (FileUploadException e) {
			e.printStackTrace();
		}
		//将已修改的图片名称返回前端
		out.print(ret_fileName);
		out.flush();
		out.close();
	}

}

  

package com.mybank.enterprise.framework.servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mybank.enterprise.util.Constant;

public class GetIMGServlet extends HttpServlet {

	private static final long serialVersionUID = 2761789171087122738L;

	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

		this.doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

		String file = req.getParameter("file");

		File pic = new File(Constant.RB.getString("img_path")+file);

		FileInputStream fis = new FileInputStream(pic);
		OutputStream os = resp.getOutputStream();
		try {
			int count = 0;
			byte[] buffer = new byte[1024 * 1024];
			while ((count = fis.read(buffer)) != -1)
				os.write(buffer, 0, count);
			os.flush();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (os != null)
				os.close();
			if (fis != null)
				fis.close();
		}

	}

}

  

Uploadify v3.2.1 上传图片并预览

时间: 2024-10-07 05:23:02

Uploadify v3.2.1 上传图片并预览的相关文章

java uploadify上传图片并预览

前一篇文章可以看到对jquery uploadify的属性的讲解,这里给出具体的java代码实现,代码基于servlet,实现了上传图片并预览的效果,不多说,上代码 index.jsp <%@ page language="java" contentType="text/html; charset=UTF-8"     pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W

上传图片带预览功能兼容IE和火狐等主流浏览器

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-

2016/4/19 ①单个文件上传 ②上传图片后 预览图片

1,f1.php <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <!-- 作业:在网上找上传图片预览的代码 上传服务器 再预览--> <form action="f1chuli.php&q

js实现上传图片本地预览功能

js: /**     * 上传图片本地预览方法     * @param {Object} fileObj 上传文件file的id元素  fresh-fileToUpload      * @param {Object} previewObj 上传图片的预览id元素  fresh-send-preview-img     * @param {Object} localImg 预览图片的父层id元素  fresh-send-preview-imgvideo     */    fs.setIma

Ajax 实现上传图片即时预览功能

本文为原创,转载请注明:http://www.pm-road.com/index.php/2014/07/31/50 很多网站在上传头像或照片的时候,都会有一个预览功能,结合自身体验将该功能实现一下:要求:图片保存到数据库点击查看实现ajax上传图片即时预览另一种方法(简单方法) 之前,我在做项目的时候,有一个功能就是要求上传的图片要即时显示,很多网站都会有这样的案例,其中的代码逻辑大多为把图片传到服务器上之后,返回图片的 物理路径,不过,我们当时使用的框架为ExtJS 4.1,而且因为涉及一些

HTML5上传图片并预览

一个简易的实现: <!DOCTYPE html> <html> <head> <title>HTML5上传图片并预览</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <script src="https://cdn.bootcss.com/jquery/2.2.4/jquery

Jcrop+uploadify+php实现上传头像预览裁剪

最近由于项目需要,所以做了一个上传头像预览并且可以预览裁剪的功能,大概思路是上传的图片先保存到服务器,然后通过ajax从服务器获取到图片信息,再利用Jcrop插件进行裁剪,之后通过PHP获取到的四个裁切点的坐标进行裁剪. 首先看一下uploadify上传插件的API: uploader : uploadify.swf 文件的相对路径,该swf文件是一个带有文字BROWSE的按钮,点击后淡出打开文件对话框,默认值:uploadify.swf.script :   后台处理程序的相对路径 .默认值:

Ajax 上传图片并预览

1. 直接上最简单的 一种 ajax 异步上传图片,并预览 html: 1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 5 <title>图片上传 | cookie</title> 6 </head> 7 <body

移动端h5实现拍照上传图片并预览

.移动端实现图片上传并预览,用到h5的input的file属性及filereader对象:经测除了android上不支持多图片上传,其他基本ok实用: 一:先说一下单张图片上传(先上代码): html结构(含多张图片容器div): 1 <div class="fileBtn"> 2 <p>点击添加图片</p> 3 <input id="fileBtn" type="file" onchange="