前端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 上传图片并预览的更多相关文章

  1. js上传图片及预览功能

    详细内容请点击 参考了网上一些人代码写了一个上传图片及时预览的功能 <img id="imgTag" style="height: 100px;" alt ...

  2. jquery解决file上传图片+图片预览

    js解决file上传图片+图片预览 demo案例中代码为js原生控制,可以根据项目的需求修改为jquery操作 <!DOCTYPE html><html lang="en& ...

  3. js实现上传图片本地预览功能以及限制图片的文件大小和尺寸大小

    方法一: js: /**     * 上传图片本地预览方法     * @param {Object} fileObj 上传文件file的id元素  fresh-fileToUpload      * ...

  4. vue <input type="file">上传图片、预览、删除

    使用原生<input type="file">上传图片.预览.删除:multiple实现可上传多张 参数名 类型 说明 fileTypes Array 文件类型, 默认 ...

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

    最近由于项目需要,所以做了一个上传头像预览并且可以预览裁剪的功能,大概思路是上传的图片先保存到服务器,然后通过ajax从服务器获取到图片信息,再利用Jcrop插件进行裁剪,之后通过PHP获取到的四个裁 ...

  6. nodejs实现本地上传图片并预览功能(express4.0+)

    Express为:4.13.1  multyparty: 4.1.2 代码主要实现本地图片上传到nodejs服务器的文件下,通过取图片路径进行图片预览 写在前面:计划实现图片上传预览功能,但是本地图片 ...

  7. (JavaScript)实现上传图片实时预览和(文件)大小判断

    唉,为什么我一个做大数据和后端的要为前端耗尽心力啊??!! 昨天在做一个网页时遇到了一个问题,有一处需要插入图片,我原本的想法是获取到上传文件的URL,然后动态插入img标签,设置src为图片的URL ...

  8. js上传图片前预览方法(支持预览多个图片)

    运用js实现上传图片前的预览(支持多张图片),实现的例子如下: 1.源码例子: 1)Js脚本页面 <!doctype html> <html> <head> < ...

  9. 移动端h5实现拍照上传图片并预览&webuploader

    .移动端实现图片上传并预览,用到h5的input的file属性及filereader对象:经测除了android上不支持多图片上传,其他基本ok实用: 一:先说一下单张图片上传(先上代码): html ...

随机推荐

  1. ASP通过代码绑定Gridview控件

    using System.Configuration;using System.Data.OleDb;using System.Data; public partial class datafilm ...

  2. 在CentOS6.7操作系统上编译安装mysql-5.6.31

    功能概述: 由于在centos 6.7下通过yum安装的mysql是5.1版本的,不满足需求,因此经常性需要编译安装mysql服务等. 一.安装mysql 1.安装前提 1)安装编译mysql代码所依 ...

  3. 「zigbee - 1」工欲善其事必先利其器 - IAR for 8051 IDE customization

    最近在实验室做一些 Zigbee 相关的事情,然而一直没在博客上记录啥东西,也不像原来在公司有动力在 Confluence wiki 上扯东扯西.直到前些阵子,跑到 feibit 论坛上(国内较大的一 ...

  4. 取td里面的内容

    var rowLength = document.getElementById("table名字").rows.length;   for(var i=0;i<rowLeng ...

  5. mvc-servlet---servletContext与servletConfig2

    在编写servlet过程中,需要用到 ServletConfig.ServletContext对象,对这两种对象的介绍如下: ServletContext对象:servlet容器在启动时会加载web应 ...

  6. 导入module

    1.http://blog.csdn.net/cryssdut/article/details/50357876 2.直接把lib复制黏贴到项目里,无法直接用:需要在 settings.gradle中 ...

  7. HTML之DOM

    对于B/S开发,客户端与服务器端的交互是非常必要的,JavaScript的提出解决了很多问题,AJAX的提出也解决了异步通信的问题,更加为用户着想了.而DOM是其中非常基础的知识,在学习AJAX的同时 ...

  8. PHP表单处理

    <?php if(isset($_POST['submit'])) { foreach ($_POST["languages"] as $item) { echo " ...

  9. Android开发笔记

    Android 中国SDK: http://wear.techbrood.com/ Android SDK Manager 代理设置: http://www.cnblogs.com/sunzn/p/4 ...

  10. [BTS] Exception occurred when persisting state to the database

    Error 1 Uncaught exception (see the 'inner exception' below) has suspended an instance of service 'J ...