//jsp头部
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
//html头部
<head>
<base href="<%=basePath%>">
head>
http://localhost:8080/system/img/a1.jpg
http://你的ip与端口/项目名称/资源文件,例如img/a1.jpg
可以参考这个,写的比较详细
http://blog.csdn.net/snannan_268/article/details/5511614
在java中路径一般用"/"
windows中的路径一般用"\"(在java中写"\",要写成"\\",因为"\"是转义符)
linux、unix中的路径一般用"/"
//注意
java是跨平台的,Linux和Unix下都是用“/”。而在windows下也能识别“/”。所以最好用“/”
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" isELIgnored="false" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<head>
<base href="<%=basePath%>">
<title>上传title>
<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">
head>
<body>
${path}
<form action="UploadTestServlet" enctype="multipart/form-data" id="loginform" name="loginform" method="post">
选择图片:<input type="file" name="filename"/>
<input id="subid" name="subid" type="submit" value="提交">
form>
body>
html>
package com.iamzhuwh.system.action;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
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.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
//注解的方式声明servlet的路径
@WebServlet("/UploadTestServlet")
public class UploadTestServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/** 上传目录名*/
private static final String UPLOAD_DIR = "uploadDir/img/";
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("UploadTestServlet in");
/****** 初始化部分 ******/
//设置编码格式,前端后台统一是utf-8
request.setCharacterEncoding("utf-8");
response.setContentType("text/json;charset=utf-8");
/****** 文件路径部分 用的是项目发布的相对路径******/
// Servlet上下文对象
ServletContext servletContext = this.getServletConfig().getServletContext();
// tomcat的项目路径,记住要加斜杠
String fileName = "test.jpg";//保存为什么名字
String realPath = servletContext.getRealPath(UPLOAD_DIR)+"/";//保存的路径
String filePath = realPath+fileName;//合起来就是完整的文件路径了
System.out.println("UploadTestServlet filePath:"+filePath);
File realPathFile = new File(realPath);
if (!realPathFile.exists()) {
realPathFile.mkdirs();
}
/****** 读写部分 ******/
FileOutputStream fos = new FileOutputStream(new File(filePath));
//传给页面的输出流
ServletInputStream sis = request.getInputStream();
byte[] b = new byte[1024];
int len = 0;;
while ((len=sis.read(b))!=-1) {
fos.write(b, 0, len);
}
/****** 关闭资源 ******/
fos.close();
sis.close();
/****** 把图片地址,转发回页面 ******/
try {
request.setAttribute("path", UPLOAD_DIR+fileName);
System.out.println("UploadTestServlet path:"+UPLOAD_DIR+fileName);
request.getRequestDispatcher("/test/UploadTest.jsp").forward(request, response);
} catch (ServletException e) {
e.printStackTrace();
}
}
}
用这种方法,图片获取后是打开不了的,或者打开错误,用notepad++或者其他编辑器打开刚才保存的文件,把头信息和尾部信息去掉,然后保存,才可以变为一张真正的图片。
------WebKitFormBoundaryBuT6WAkLnldFCDJ0
Content-Disposition: form-data; name="filename"; filename="error.png"
Content-Type: image/png
塒NG
IHDR ? ? Z蟻 sRGB ? gAMA 睆黙 DVIDATx^磔鞒,U?瘃猒s??
JP藤R薘?TY鷽摽櫵褺硞QD0媌罍sx啕嬴譵畿s蜭鱈蠝~??灥邹换蟤1?14?"8r銱勐?倏mns涃韓w?溄跫t圹薅骺巾K?镞砡棾_W尺烦啐顆-?烗醑m?_PI??mH>俾??w顾]fw葵蒇訾揘気?鳂蓣诀m?冧擈陕9yT9賥?H}甑幧?跜?P?唼龇o戙鳪;餃龇?僨攲疡_椂u-#et?)曄俭踯A‖Z钵顮LI9?钚浑註[渟
嚔#抗??鏈s輨鉸鑬8=脠A5?&@(唘?吖隢w篠;n瑰栙~饍傧?f?ㄤ>e$鬻?字{8勪R詚 ?飜侵婚轭s燐填w葵祎坊輒v瘂莴]$魑#斶?贕?拧'鉆溳€(栏x??傿皁}隱筹麔€蜧6e捏囓甅倫M
......
......
......
膜嚍L?%?D?!|b€橳@6/顷齶灾?R0d?噺宏?濤zN?]脳?靤M??蹑藆z0廙榕?亵b!X ?I欅R鲘塸=!?n鬷?絖哖
Y驪祘绌?鬪勊婽偤 梌J覌y∮?b!涍鏏[RV驔pp???垾桯狭?$?徉8傻H?4?!僋r?$\_髳HR銾吩O颶?采K=唀?=雏輧l蝛髣僠6?鷂?C閫 IEND瓸`?
------WebKitFormBoundaryBuT6WAkLnldFCDJ0
Content-Disposition: form-data; name="subid"
鎻愪氦
------WebKitFormBoundaryBuT6WAkLnldFCDJ0--
塒NG
IHDR ? ? Z蟻 sRGB ? gAMA 睆黙 DVIDATx^磔鞒,U?瘃猒s??
JP藤R薘?TY鷽摽櫵褺硞QD0媌罍sx啕嬴譵畿s蜭鱈蠝~??灥邹换蟤1?14?"8r銱勐?倏mns涃韓w?溄跫t圹薅骺巾K?镞砡棾_W尺烦啐顆-?烗醑m?_PI??mH>俾??w顾]fw葵蒇訾揘気?鳂蓣诀m?冧擈陕9yT9賥?H}甑幧?跜?P?唼龇o戙鳪;餃龇?僨攲疡_椂u-#et?)曄俭踯A‖Z钵顮LI9?钚浑註[渟
嚔#抗??鏈s輨鉸鑬8=脠A5?&@(唘?吖隢w篠;n瑰栙~饍傧?f?ㄤ>e$鬻?字{8勪R詚 ?飜侵婚轭s燐填w葵祎坊輒v瘂莴]$魑#斶?贕?拧'鉆溳€(栏x??傿皁}隱筹麔€蜧6e捏囓甅倫M
......
......
......
膜嚍L?%?D?!|b€橳@6/顷齶灾?R0d?噺宏?濤zN?]脳?靤M??蹑藆z0廙榕?亵b!X ?I欅R鲘塸=!?n鬷?絖哖
Y驪祘绌?鬪勊婽偤 梌J覌y∮?b!涍鏏[RV驔pp???垾桯狭?$?徉8傻H?4?!僋r?$\_髳HR銾吩O颶?采K=唀?=雏輧l蝛髣僠6?鷂?C閫 IEND瓸`?
commons-fileupload(java中引入)
webUploader(jsp中引入)
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" isELIgnored="false" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<head>
<base href="<%=basePath%>">
<title>上传title>
<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">
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.0.js">script>
<script type="text/javascript" src="utils/webuploader/webuploader.js">script>
<link rel="stylesheet" href="utils/webuploader/webuploader.css" type="text/css" />
<script type="text/javascript" src="utils/webuploader/webuploader.min.js">script>
head>
<body>
<div id="uploader" class="wu-example">
<div id="thelist" class="uploader-list">div>
<div class="btns">
<div id="picker">选择文件div>
<button id="ctlBtn" class="btn btn-default">开始上传button>
div>
div>
body>
<script type="text/javascript">
$(function () {
/****** 初始化 ******/
var $ = jQuery,
$list = $('#thelist'),
$btn = $('#ctlBtn'),
state = 'pending',
ratio = window.devicePixelRatio || 1,
thumbnailWidth = 100 * ratio,
thumbnailHeight = 100 * ratio,
uploader;
//初始化
uploader = WebUploader.create({
// 选完文件后,是否自动上传。
auto: false,
// swf文件路径
//swf: BASE_URL + '/js/Uploader.swf',
// 文件接收服务端。
server: 'UploadTestServlet',
// 选择文件的按钮。可选。
// 内部根据当前运行是创建,可能是input元素,也可能是flash.
pick: '#picker',
// 只允许选择图片文件。
accept: {
title: 'Images',
extensions: 'gif,jpg,jpeg,bmp,png',
mimeTypes: 'image/*'
}
});
/****** 选择文件 ******/
// 当有文件添加进来的时候
uploader.on( 'fileQueued', function( file ) {
var $li = $(
''" class="file-item thumbnail">' +
'
' +
'' + file.name + '' +
''
),
$img = $li.find('img');
// $list为容器jQuery实例
$list.append( $li );
// 创建缩略图
// 如果为非图片文件,可以不用调用此方法。
// thumbnailWidth x thumbnailHeight 为 100 x 100
uploader.makeThumb( file, function( error, src ) {
if ( error ) {
$img.replaceWith('不能预览');
return;
}
$img.attr( 'src', src );
}, thumbnailWidth, thumbnailHeight );
});
/****** 上传状态 ******/
// 文件上传过程中创建进度条实时显示。
uploader.on( 'uploadProgress', function( file, percentage ) {
var $li = $( '#'+file.id ),
$percent = $li.find('.progress span');
// 避免重复创建
if ( !$percent.length ) {
$percent = $('
')
.appendTo( $li )
.find('span');
}
$percent.css( 'width', percentage * 100 + '%' );
});
// 文件上传成功,给item添加成功class, 用样式标记上传成功。
uploader.on( 'uploadSuccess', function( file ) {
$( '#'+file.id ).addClass('upload-state-done');
});
// 文件上传失败,显示上传出错。
uploader.on( 'uploadError', function( file ) {
var $li = $( '#'+file.id ),
$error = $li.find('div.error');
// 避免重复创建
if ( !$error.length ) {
$error = $('').appendTo( $li );
}
$error.text('上传失败');
});
// 完成上传完了,成功或者失败,先删除进度条。
uploader.on( 'uploadComplete', function( file ) {
$( '#'+file.id ).find('.progress').remove();
});
/****** 上传按钮 ******/
//上传的按键
$btn.on( 'click', function() {
if ( state === 'uploading' ) {
uploader.stop();
} else {
uploader.upload();
}
});
});
script>
html>
package com.iamzhuwh.system.action;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
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.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
//注解的方式声明servlet的路径
@WebServlet("/UploadTestServlet")
public class UploadTestServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/** 上传目录名*/
private static final String UPLOAD_DIR = "uploadDir/img/";
/** 上传临时文件存储目录*/
private static final String TEMP_UPLOAD_DIR ="uploadDir/temp/";
/** 总上传文件最大为10M*/
private static final Long TOTAL_FILE_MAXSIZE = 10000000L;
/** 单个上传文件最大为10M*/
private static final int SINGLE_FILE_MAXSIZE = 2*1024*1024;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("UploadTestServlet in");
//设置编码格式,前端后台统一是utf-8
request.setCharacterEncoding("utf-8");
response.setContentType("text/json;charset=utf-8");
//
PrintWriter out = response.getWriter();
// Servlet上下文对象
ServletContext servletContext = this.getServletConfig().getServletContext();
// tomcat的项目路径
String realPath = servletContext.getRealPath(UPLOAD_DIR)+"/";
String tempPath = servletContext.getRealPath(TEMP_UPLOAD_DIR)+"/";
File tempPathFile = new File(tempPath);
File realPathFile = new File(realPath);
if (!tempPathFile.exists()) {
tempPathFile.mkdirs();
}
if (!realPathFile.exists()) {
realPathFile.mkdirs();
}
// 文件对象的工厂类
DiskFileItemFactory factory = new DiskFileItemFactory();
// 设置最大上传大小
factory.setSizeThreshold(SINGLE_FILE_MAXSIZE);
// 将临时文件夹交给文件对象的工厂类
factory.setRepository(tempPathFile);
// 创建一个上传文件的处理者
ServletFileUpload upload = new ServletFileUpload(factory);
// 设置所有请求的总大小
upload.setSizeMax(TOTAL_FILE_MAXSIZE);
// 解析request
List items;
try {
items = upload.parseRequest(request);
// 处理解析处理的请求对象
Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = iter.next();
//判断是文件还是文本
if (!item.isFormField()) {
//文件名加上UUid,可以防止重复
//String fileName = UUID.randomUUID().toString().replace("-", "")+"_"+item.getName();
String fileName = item.getName();
System.out.println("UploadTestServlet file path:"+UPLOAD_DIR+fileName);
//判断空
if (fileName!=null && !"".equals(fileName)) {
//将文件写到硬盘
item.write(new File(realPath+fileName));
//将图片地址保存到request中,再转发回给jsp
//UPLOAD_DIR+fileName这个是相对路径,给前端页面
//realPath+fileName是绝对路径
//request.setAttribute("path", UPLOAD_DIR+fileName);
//request.getRequestDispatcher("/test/UploadTest.jsp").forward(request, response);
out.write("ok");
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}