日期:2014-05-17  浏览次数:20809 次

图片上传的问题
要求上传图片到服务器目录文件夹下,以用户名+用户Id.img修改图片名称,并且将路径保存到数据库中,如果没有图片则存默认图片路径、photo/0.jgp,这个应该怎么做啊,有没有谁有这方面的源码,麻烦贴出来借鉴一下,感激不尽啊

------解决方案--------------------
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="java.io.*" %>
<%@ page import="com.sun.image.codec.jpeg.*" %>
<%@ page import="java.awt.image.*" %>
<%@ page import="java.awt.*" %>
<%@ page import="java.util.*"%>
<%@ page import="java.text.*"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<% 
String name = request.getParameter("name");
//name = new String(name.getBytes("ISO-8859-1"));
String ima = request.getParameter("image");
try{
String path = request.getRealPath("/");
FileOutputStream ot = new FileOutputStream(path + name + ".jpg");
out.print(ot);
FileInputStream in = new FileInputStream(ima);
JPEGImageDecoder jpgCodec = JPEGCodec.createJPEGDecoder(in);
BufferedImage image = jpgCodec.decodeAsBufferedImage();
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(ot);
encoder.encode(image);
in.close();
ot.close();
out.print("图片上传成功!<br>");
out.print("<IMG width=200 heigh=200 src='"+name+".jpg'/>");
}catch(Exception e){
System.out.print(e.toString());
}
%>
</body>
</html>
------解决方案--------------------
public String upload(String dir, FormFile formFile) throws Exception {
Date date = new Date();
// 取欲上传的文件的名字和长度
String fname = formFile.getFileName();
// 将上传时间加入文件名
int i = fname.indexOf(".");
String name = String.valueOf(date.getTime());
String type = fname.substring(i + 1);
fname = name + "." + type;
InputStream streamIn = formFile.getInputStream(); // 创建读取用户上传文件的对象
File uploadFile = new File(dir); // 创建把上传数据写到目标文件的对象
if (!uploadFile.exists() || uploadFile == null) { // 判断指定路径是否存在,不存在则创建路径
uploadFile.mkdirs();
}
String path = uploadFile.getPath() + "/" + fname;
OutputStream streamOut = new FileOutputStream(path);
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = streamIn.read(buffer, 0, 8192)) != -1) {
streamOut.write(buffer, 0, bytesRead);
}
streamOut.close();
streamIn.close();
formFile.destroy();
return fname;
}

直接调用这个上传的方法就行了。