日期:2014-05-18  浏览次数:20763 次

jsp中如何存储上传的图片
我希望将上传的图片存到指定的文件夹中,然后将这个路径存到数据库中.
阅读了很多帖子,但是还是没明白.

很多文章中都提到了smartupload.我也下载了一个,在网上查了如何设置,但是没有在smartupload中找到大家说的文件夹.我解压以后有六个文件.名字分别为:ServletUpload     SmartFile   SmartFiles   SmartRequest   SmartUpload   SmartUploadException.不知该如何使用?

------解决方案--------------------
package com.ts;

import org.apache.struts.upload.FormFile;

import java.io.InputStream;
import java.io.OutputStream;
import java.io.FileOutputStream;
import java.lang.String;

public class Upload {
String dir = " ";
String fileType = " ";
FormFile file = null;

public Upload(FormFile file,String dir){
this.file = file;
this.dir = dir;
}

public boolean upload() throws Exception{
boolean flag = true;
// 获取上传的图片文件名
String fileName = file.getFileName();

// 只有图像的名字不为空时,并且类型正确时才进行上传动作
if(fileName!=null&&!fileName.equals( " ")){
int point = fileName.lastIndexOf( '. ');
//如果文件名中不包含 ' . ' 返回错误信息
if(point == -1){
fileType = " ";
flag = false;
}else{
//获取上传的图片文件名的扩展名
fileType = fileName.substring(point).toLowerCase();

//限止上传文件的类型
if( ".jpg ".equalsIgnoreCase(fileType)|| ".gif ".equalsIgnoreCase(fileType)||
".bmp ".equalsIgnoreCase(fileType)|| ".doc ".equalsIgnoreCase(fileType)||
".zip ".equalsIgnoreCase(fileType)){
//开始上传图片文件
InputStream streamIn = file.getInputStream();
OutputStream StreamOut = new FileOutputStream(dir+fileType);
//System.out.println(dir+fileType);

byte[] buffer = new byte[8192];
int bytesRead = 0;
while ((bytesRead = streamIn.read(buffer, 0, 8192)) != -1) {
StreamOut.write(buffer, 0, bytesRead);
}
StreamOut.close();
streamIn.close();
} else {
fileType = " ";
flag = false;
}
}
}
return flag;
}

public String getDir() {
return dir;
}

public void setDir(String dir) {
this.dir = dir;
}

public String getFileType() {
return fileType;
}

public void setFileType(String fileType) {
this.fileType = fileType;
}
}


供参考
------解决方案--------------------
protected void doGet(HttpServletRequest arg0, HttpServletResponse arg1)
throws ServletException, IOException {
SmartUpload upload = new SmartUpload();

//初始化数据
upload.initialize(this.getServletConfig(),arg0,arg1);
//设置每个上传文件的大小
upload.setMaxFileSize(1028*10);
//设置所有上传文件的总大小
upload.setTotalMaxFileSize(1028*10*10);
//设置上传文件的类型
upload.service(arg0,arg1);


try{