java 图片的上传总结
2016-09-19 16:09
302 查看
jsp中上传图片,整理别人的文章,自己测试后又加入了其他方法
需求:前台选择图片,页面显示上传后的图片地址
代码一(方法1): form 提交,获取不了返回值,会刷新页面
<form id="uploadForm" action="http://xxxx/xxx/xx/images/upload?token=tokenstring" method="post" enctype="multipart/form-data">
<table>
<tr>
<td width="100" align="right">图片:</td>
<td><input type="file" name="img"/> <input type="submit" value="Submit"></td>
</tr>
</table>
</form>
代码一(方法2):ajaxUploadImg.jsp,可以有返回值,不刷新页面
百度搜索,并下载jquery.js 及 ajaxfileupload.js
[html] view
plain copy
print?
<%@ 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', //需要链接到服务器地址
//url:'/xxx/xxx/xxx/images/upload.htm?token=tokenstring',//适用于方法一
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" />
<a href="#" id="buttonUpload" onclick="return ajaxFileUpload();" >上传</a>
<!-- 上面必须用<a 必须加上href="#" -->
</form>
</html>
代码二(方法1):springMVC
我用的这个方法,方法2 没试
//上传图片的接口
@RequestMapping( value = "/xxxx/images/upload.htm", method = {RequestMethod.POST})
@ResponseBody
public String uploadGoodsCategoryImages(HttpServletRequest req) throws IOException
{
System.out.println("upload-img---------------");
//tomcat中文件储存路径,tomcat文件路径
//需要刷新及时刷新,但可以解决,在server.xml中配置:
//<Context docBase="D:\eclipse_workspace\xxxx\WebContent\categoryimages" path="/xxxx/categoryimages" debug="0" reloadable="fasle" privilege="true"/>
String realDir = req.getSession().getServletContext().getRealPath("");
//tomcat中项目如:C:\apache-tomcat-7.0.70\wtpwebapps\xxxx\
String filePath = "categoryimages\\";
String realPath = realDir+"\\"+filePath;
//tomcat中文件路径C:\apache-tomcat-7.0.70\wtpwebapps\xxxx\categoryimages
DiskFileItemFactory factory = new DiskFileItemFactory();
// 设置文件上传路径
String upload = realPath;
String temp = System.getProperty("java.io.tmpdir");
factory.setSizeThreshold(1024 * 1024 * 5);
factory.setRepository(new File(temp));
ServletFileUpload servletFileUpload = new ServletFileUpload(factory);
try
{
List<FileItem> list = servletFileUpload.parseRequest(req);
for (FileItem item : list)
{
String name = item.getFieldName();
InputStream is = item.getInputStream();
try
{
String img_name = comm.buildID20()+".jpg"; //图片名字
inputStream2File(is, upload + img_name);
String img_url = comm.CONTEXTIMGPATH+"/xxx/"+img_name;
return String.format("{\"img_url\":\""+img_url+"\""
+ ",\"status\":\"success\"}");
} catch (Exception e)
{
e.printStackTrace();
}
}
} catch (FileUploadException e)
{
return ”未知错误,请稍后再试“;
}
return String.format(upload);
}
代码二(方法2): FileUpload.java
这里使用了commons-fileupload-1.2.1.jar的包,可以自行搜索下载
如果使用myeclipse,可以直接在Struts 2 Core Libraies中找到.
commons-fileupload-1.2.1.jar
[java] view
plain copy
print?
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做如下
[html] view
plain copy
print?
<?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>
需求:前台选择图片,页面显示上传后的图片地址
代码一(方法1): form 提交,获取不了返回值,会刷新页面
<form id="uploadForm" action="http://xxxx/xxx/xx/images/upload?token=tokenstring" method="post" enctype="multipart/form-data">
<table>
<tr>
<td width="100" align="right">图片:</td>
<td><input type="file" name="img"/> <input type="submit" value="Submit"></td>
</tr>
</table>
</form>
代码一(方法2):ajaxUploadImg.jsp,可以有返回值,不刷新页面
百度搜索,并下载jquery.js 及 ajaxfileupload.js
[html] view
plain copy
print?
<%@ 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', //需要链接到服务器地址
//url:'/xxx/xxx/xxx/images/upload.htm?token=tokenstring',//适用于方法一
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" />
<a href="#" id="buttonUpload" onclick="return ajaxFileUpload();" >上传</a>
<!-- 上面必须用<a 必须加上href="#" -->
</form>
</html>
代码二(方法1):springMVC
我用的这个方法,方法2 没试
//上传图片的接口
@RequestMapping( value = "/xxxx/images/upload.htm", method = {RequestMethod.POST})
@ResponseBody
public String uploadGoodsCategoryImages(HttpServletRequest req) throws IOException
{
System.out.println("upload-img---------------");
//tomcat中文件储存路径,tomcat文件路径
//需要刷新及时刷新,但可以解决,在server.xml中配置:
//<Context docBase="D:\eclipse_workspace\xxxx\WebContent\categoryimages" path="/xxxx/categoryimages" debug="0" reloadable="fasle" privilege="true"/>
String realDir = req.getSession().getServletContext().getRealPath("");
//tomcat中项目如:C:\apache-tomcat-7.0.70\wtpwebapps\xxxx\
String filePath = "categoryimages\\";
String realPath = realDir+"\\"+filePath;
//tomcat中文件路径C:\apache-tomcat-7.0.70\wtpwebapps\xxxx\categoryimages
DiskFileItemFactory factory = new DiskFileItemFactory();
// 设置文件上传路径
String upload = realPath;
String temp = System.getProperty("java.io.tmpdir");
factory.setSizeThreshold(1024 * 1024 * 5);
factory.setRepository(new File(temp));
ServletFileUpload servletFileUpload = new ServletFileUpload(factory);
try
{
List<FileItem> list = servletFileUpload.parseRequest(req);
for (FileItem item : list)
{
String name = item.getFieldName();
InputStream is = item.getInputStream();
try
{
String img_name = comm.buildID20()+".jpg"; //图片名字
inputStream2File(is, upload + img_name);
String img_url = comm.CONTEXTIMGPATH+"/xxx/"+img_name;
return String.format("{\"img_url\":\""+img_url+"\""
+ ",\"status\":\"success\"}");
} catch (Exception e)
{
e.printStackTrace();
}
}
} catch (FileUploadException e)
{
return ”未知错误,请稍后再试“;
}
return String.format(upload);
}
代码二(方法2): FileUpload.java
这里使用了commons-fileupload-1.2.1.jar的包,可以自行搜索下载
如果使用myeclipse,可以直接在Struts 2 Core Libraies中找到.
commons-fileupload-1.2.1.jar
[java] view
plain copy
print?
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做如下
[html] view
plain copy
print?
<?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>
相关文章推荐
- spring注解方式在一个普通的java类里面注入dao
- 记录学习的点滴(Spring注解学习过程中问题总结)
- 手把手Maven搭建SpringMVC+Spring+MyBatis框架(超级详细版)【转】
- 深入理解java虚拟机第二章
- Java 数组
- Maven搭建SpringMVC+Mybatis项目详解【转】
- Zookeeper Api(java)入门与应用(转)
- jdk1.5-1.9新特性
- Mybatis3+Spring4+SpringMVC4 整合【转】
- springboot一个service内组件的加载顺序
- Struts2+Spring4+myBatis3整合
- JAVA EE-JSP
- Spring定时任务的几种实现
- 转:全面分析 Spring 的编程式事务管理及声明式事务管理
- JAVA字符串格式化-String.format()的使用
- spring定时任务配置
- maven 学习(一) 在 eclipse 中的安装
- 一个用Java实现的双向队列,可以分别在头尾插入和删除节点
- java -- hashcode相关的内容
- java 测试mysql 最大连接