前端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. struts2 struts1.x 区别

    此文转于http://www.blogjava.net/sterning/archive/2007/07/17/130892.html Struts作为MVC 2的Web框架,自推出以来不断受到开发者 ...

  2. [Leetcode][JAVA] Word Ladder II

    Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) from ...

  3. SQL语句汇总(一)——数据库与表的操作以及创建约束

    首先,非常感谢大家对上篇博文的支持,真是让本菜受宠若惊,同时对拖了这么久才出了此篇表示抱歉. 前言:此文旨在汇总从建立数据库到联接查询等绝大部分SQL语句.SQL语句虽不能说很多,但稍有时间不写就容易 ...

  4. azure之MSSQL服务性能测试

    azure给我们提供非常多的服务而这些服务可以让企业轻而易举地在上构建一个健壮的服务体系.但在使用azure的相关产品服务时还是应该对相关的服务有一些简单的性能了解才能更好的让企业购买适合自己的服务产 ...

  5. 使用NHibernate(9)-- 缓存

    1,对象状态. 作为基础,还是先看一下对象的状态吧.主要涉及到三个名词,瞬时.持久.托管. 瞬时态:对象刚创建,Session还不知道这个对象的存在.可以通过调用ISession的Save等方法可以转 ...

  6. EmberJs之3W

    写在前面 最近比较忙,换了新工作还要学习很多全新的技术栈,并给自己找了很多借口来不去坚持写博客.常常具有讽刺意味的是,更多剩下的时间并没有利用而更多的是白白浪费,也许这就是青春吧,挥霍吧,这不是我想要 ...

  7. 解析ASP.NET WebForm和Mvc开发的区别

    因为以前主要是做WebFrom开发,对MVC开发并没有太深入的了解.自从来到创新工场的新团队后,用的技术都是自己以前没有接触过的,比如:MVC 和EF还有就是WCF,压力一直很大.在很多问题都是不清楚 ...

  8. [ACM_几何] Metal Cutting(POJ1514)半平面割与全排暴力切割方案

    Description In order to build a ship to travel to Eindhoven, The Netherlands, various sheet metal pa ...

  9. Jenkins与.NET项目

    转自: https://blog.dangl.me/categories Continuous Integration RSS Date Post 2016-10-20 Set Up Private ...

  10. C#调用dll提示"试图加载格式不正确的程序"解决方法

    程序在32位操作系统上运行正常,在64位操作系统上运行读卡功能提示”试图加载格式不正确“. ------------------------------------------------------ ...