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{
//设置禁止上传的文件类型
//upload.setDeniedFilesList( "exe,rar,bat ");
upload.upload();
upload.setAllowedFilesList( "doc,txt,xls ");
//保存文件
Files files= upload.getFiles();
System.out.println( "files count: "+files.getCount());
for(int i=0;i <files.getCount();i++){
File file = files.getFile(i);
if(file.isMissing()) continue;
file.saveAs( "e:\\ "+file.getFileName());
}
PrintWriter out = arg1.getWriter();
out.println( " <script> alert( 'success '); </script> ");
out.flush();
out.close();
} catch (Exception e) {
}
}
[解决办法]
你把包导入到项目里是可以用的,SmartUpload里有上传下载的方法