黑马程序员技术交流社区
标题:
分享一个上传图片到服务器的工具类
[打印本页]
作者:
yangcy
时间:
2014-7-12 13:53
标题:
分享一个上传图片到服务器的工具类
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.directwebremoting.WebContext;
import org.directwebremoting.WebContextFactory;
public class UploadImageUtil {
private UploadImageUtil() {
}
public static String uploadImage(String goodsPhoto) {
// 截取图片路径的前面部分,获取图片名称部分
goodsPhoto = goodsPhoto.substring(12);
String goodsPhotoUrl = goodsPhoto;
WebContext webContext = WebContextFactory.get();
// 图片存放在服务器上的路径
String goodsUrl = webContext.getHttpServletRequest().getSession()
.getServletContext().getRealPath("/images/goodsPhotos");
// 获取系统当前时间
long nowTime = System.currentTimeMillis();
// 定义一个格式化日期对象
SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
Date date = new Date(nowTime);
// 格式化日期
String strDate = format.format(date);
// 拼接目标地址
goodsUrl += "\\" + strDate + ".jpg";
FileInputStream in = null;
FileOutputStream out = null;
try {
// 读取文件
in = new FileInputStream(goodsPhotoUrl);
// 创建文件
File file = new File(goodsUrl);
// 如果文件不存在
if (!file.exists()) {
// 创建一个文件
file.createNewFile();
}
// 写出文件
out = new FileOutputStream(file);
int ch = -1;
byte[] buffer = new byte[1024];
while ((ch = in.read(buffer)) != -1) {
out.write(buffer);
out.flush();
}
out.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
in.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// 返回图片在服务上的图片名称
return strDate + ".jpg";
}
}
复制代码
分析:上传图片到tomcat服务器,说白了就是将源路径中的图片资源读取后,写到目的tomcat服务器相应的路径中。
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2