java实现图片上传至服务器并显示,如何做?

目标很简单,通过JSP页面让用户选择本地图片文件,提交就上传到服务器保存。上传成功的话JSP页面上就显示刚上传的图片。

我自己想了一下,觉得有两种办法可以试试:
1、服务器把图片作为blob型数据存进数据库,然后显示的时候就查数据库取出来送到JSP
2、服务器把图片作为文件保存到服务器某个文件夹,例如upload文件夹,然后把图片的路径名作为varchar型保存到数据库中。显示的时候就到数据库中查找路径名,处理后赋值给<img>的src属性

我想知道的是:
1、服务器端怎么从浏览器接收文件,通过流吗?如果是流那么用什么流呢?字节流、字符流或者其它的高级流?服务器接收到的文件是个什么样子?例如上传的是jpg图片,服务器最初接收到的就是.jpg的文件吗?

2、对于第一种实现方法,把blob数据从数据库取出来之后是什么样子?例如当初jpg图片作blob存进去的,取出来之后就是jpg的吗?还是要通过什么方法做成jpg?如果要做,怎么弄呢?常见的网页显示图片代码是<img src='图片URL'>,如果是数据库取出来的图片文件,要怎么在JSP中显示?

3、对于第二种实现方法,如果第一个问题解决的话,我自己琢磨吧。感觉这个方法好理解一些

-----------------------------------------------------------------
最好能有具体代码说明一下怎么做的,谢谢!!!

给你段代码,是用来在ie上显示图片的(servlet):

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String id = request.getParameter("id");
File file = new File(getServletContext().getRealPath("/")+"out"+"/"+id+".gif");
response.setCharacterEncoding("gb2312");
response.setContentType("doc");
response.setHeader("Content-Disposition", "attachment; filename=" + new String(file.getName().getBytes("gb2312"),"iso8859-1"));

System.out.println(new String(file.getName().getBytes("gb2312"),"gb2312"));

OutputStream output = null;
FileInputStream fis = null;
try
{
output = response.getOutputStream();
fis = new FileInputStream(file);

byte[] b = new byte[1024];
int i = 0;

while((i = fis.read(b))!=-1)
{

output.write(b, 0, i);
}
output.write(b, 0, b.length);

output.flush();
response.flushBuffer();
}
catch(Exception e)
{
System.out.println("Error!");
e.printStackTrace();
}
finally
{
if(fis != null)
{
fis.close();
fis = null;
}
if(output != null)
{
output.close();
output = null;
}
}

}

这个程序的功能是根据传入的文件名(id),来为浏览器返回图片流,显示在<img>标签里
标签的格式写成如下:
<img src="http://localhost:8080/app/preview?id=111 "/><br/>
显示的是111.gif这个图片

你上面的问题:
1.我觉得你的第二个办法是对的,我们也是这样做的,需要的是把数据库的记录id号传进servlet,然后读取这条记录中的路径信息,生成流以后返回就是了

关于上传文件的问题,我记得java中应该专门有个负责文件上传的类,你调用就行了,上传后存储在指定的目录里,以实体文件的形式存放
你可以参考这个:
http://blog.csdn.net/arielxp/archive/2004/09/28/119592.aspx

回复:
1.是的,在response中写入流就行了
2.是发到servlet中的,我们一般都是写成servlet,短小精悍,使用起来方便,struts应该也可以,只是我没有试过,恩,你理解的很对
温馨提示:答案为网友推荐,仅供参考
第1个回答  2008-06-25
网上可以下到上传控件。。都是写好的 我这也有 太长了就不发上来了 你要是要我可以给你 你只要在servlet里调用里面的方法就行了
第2个回答  2015-12-06
  使用一些已有的组件帮助我们实现这种上传功能。
  常用的上传组件:
    Apache 的 Commons FileUpload
    JavaZoom的UploadBean
    jspSmartUpload
以下,以FileUpload为例讲解
1、在jsp端
<form id="form1" name="form1" method="post" action="servlet/fileServlet" enctype="multipart/form-data">
要注意enctype="multipart/form-data"
然后只需要放置一个file控件,并执行submit操作即可
<input name="file" type="file" size="20" >
<input type="submit" name="submit" value="提交" >
2、web端
核心代码如下:
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List items = upload.parseRequest(request);
Iterator itr = items.iterator();
while (itr.hasNext()) {
FileItem item = (FileItem) itr.next();
if (item.isFormField()) {
System.out.println("表单参数名:" + item.getFieldName() + ",表单参数值:" + item.getString("UTF-8"));
} else {
if (item.getName() != null && !item.getName().equals("")) {
System.out.println("上传文件的大小:" + item.getSize());
System.out.println("上传文件的类型:" + item.getContentType());
System.out.println("上传文件的名称:" + item.getName());
File tempFile = new File(item.getName());
File file = new File(sc.getRealPath("/") + savePath, tempFile.getName());
item.write(file);
request.setAttribute("upload.message", "上传文件成功!");
}else{
request.setAttribute("upload.message", "没有选择上传文件!");
}
}
}
}catch(FileUploadException e){
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
request.setAttribute("upload.message", "上传文件失败!");
}
request.getRequestDispatcher("/uploadResult.jsp").forward(request, response);
}
第3个回答  2008-06-25
用common-fileupload几行代码搞定
第4个回答  2008-06-27
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response){
RecordForm rform=(RecordForm)form;
FormFile formFile=rform.getImage();
String path=request.getSession().getServletContext().getRealPath("/");
RecordService service=(RecordService) BeanFactory.getBean(BeanFactory.RECORDSERVICE);
StudentService stuservice=(StudentService) BeanFactory.getBean(BeanFactory.STUDENTSERVICE);
Student student=(Student) request.getSession().getAttribute("student");
Record record=(Record) request.getSession().getAttribute("record");
student.setName(rform.getName());
student.setGender(rform.getGender());
record.setAddress(rform.getAddress());
record.setAdmitdate(Date.valueOf(rform.getAdmitdate()));
record.setBirthday(Date.valueOf(rform.getBirthday()));
record.setFromaddr(rform.getFromaddr());
record.setRemarks(rform.getRemarks());
record.setFeature(rform.getFeature());
record.setStudent(student);
student.setRecord(record);
if(formFile.getFileSize()!=0){
String image=getPath(formFile,path,student.getId());
record.setImage(image);
}
try {
stuservice.updateStudent(student);
service.updateRecord(record);
request.setAttribute("record", record);
request.setAttribute("student", student);
return mapping.findForward("success");
} catch (ServiceException e) {
request.setAttribute("error", e.getMessage());
e.printStackTrace();
return mapping.findForward("failure");
}
}
private String getPath(FormFile formFile, String path, String studentid) {
InputStream is = null;
FileOutputStream fos = null;
File file = new File(path + "/" + studentid + "/");
if (!file.exists())
file.mkdir();
try {
is = formFile.getInputStream();
fos = new FileOutputStream(path + "/" + studentid + "/"
+ formFile.getFileName());
byte[] buffer = new byte[8092];
int count = 0;
while ((count = is.read(buffer, 0, buffer.length)) != -1)
fos.write(buffer, 0, count);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if (is != null)
is.close();
if (fos != null)
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
return "/"+ studentid+"/"+formFile.getFileName();
}
}

用struts做的,在JSP页面中用fromFile标签
相似回答