jsp上传目录
❶ jsp上传下载文件的路径问题
jsp上传下载文件的路径是在服务器建立指定路径如下:
//接收上传文件内容中临时文件的文件名
String tempFileName = new String("tempFileName");
//tempfile 对象指向临时文件
File tempFile = new File("D:/"+tempFileName);
//outputfile 文件输出流指向这个临时文件
FileOutputStream outputStream = new FileOutputStream(tempFile);
//得到客服端提交的所有数据
InputStream fileSourcel = request.getInputStream();
//将得到的客服端数据写入临时文件
byte b[] = new byte[1000];
int n ;
while ((n=fileSourcel.read(b))!=-1){
outputStream.write(b,0,n);
}
//关闭输出流和输入流
outputStream.close();
fileSourcel.close();
//randomFile对象指向临时文件
RandomAccessFile randomFile = new RandomAccessFile(tempFile,"r");
//读取临时文件的第一行数据
randomFile.readLine();
//读取临时文件的第二行数据,这行数据中包含了文件的路径和文件名
String filePath = randomFile.readLine();
//得到文件名
int position = filePath.lastIndexOf('\\');
CodeToString codeToString = new CodeToString();
String filename = codeToString.codeString(filePath.substring(position,filePath.length()-1));
//重新定位读取文件指针到文件头
randomFile.seek(0);
//得到第四行回车符的位置,这是上传文件数据的开始位置
long forthEnterPosition = 0;
int forth = 1;
while((n=randomFile.readByte())!=-1&&(forth<=4)){
if(n=='\n'){
forthEnterPosition = randomFile.getFilePointer();
forth++;
}
}
//生成上传文件的目录
File fileupLoad = new File("D:/work space/JSP workspace/jsp_servlet_upAndLoad/file","upLoad");
fileupLoad.mkdir();
//saveFile 对象指向要保存的文件
File saveFile = new File("D:/work space/JSP workspace/jsp_servlet_upAndLoad/file/upLoad",filename);
RandomAccessFile randomAccessFile = new RandomAccessFile(saveFile,"rw");
//找到上传文件数据的结束位置,即倒数第四行
randomFile.seek(randomFile.length());
long endPosition = randomFile.getFilePointer();
int j = 1;
while((endPosition>=0)&&(j<=4)){
endPosition--;
randomFile.seek(endPosition);
if(randomFile.readByte()=='\n'){
j++;
}
}
//从上传文件数据的开始位置到结束位置,把数据写入到要保存的文件中
randomFile.seek(forthEnterPosition);
long startPoint = randomFile.getFilePointer();
while(startPoint<endPosition){
randomAccessFile.write(randomFile.readByte());
startPoint = randomFile.getFilePointer();
}
//关闭文件输入、输出
randomAccessFile.close();
randomFile.close();
tempFile.delete();
jsp文件下载选择路径:
//要下载的文件
File fileload = new File("D:/work space/JSP workspace/jsp_servlet_upAndLoad/file/upLoad",filename);
前段时间做了一个文件上传ftp功能,你参照一下
package com.ftp.upload;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
public class FTPUpload {
private FTPClient ftpClient = null;
private OutputStream outSteam = null;
/**
* ftp服务器地址
*/
private String hostname = "192.168.1.2";
/**
* ftp服务器端口
*/
int port = 21;
/**
* 登录名
*/
private String username = "admin";
/**
* 登录密码
*/
private String password = "admin";
/**
* 需要访问的远程目录
*/
private String remoteDir = "/home/demo";
public FTPUpload() { }
public FTPUpload(String hostname, int port, String username, String password, String remoteDir){
this.hostname = hostname;
this.port = port;
this.username = username;
this.password = password;
this.remoteDir = remoteDir;
}
/**
* 连接FTP服务器 并登录
* @param hostName FTP服务器hostname
* @param port FTP服务器端口
* @param username FTP登录账号
* @param password FTP登录密码
*/
private FTPClient connectFTPServer() {
try {
//1.创建FTPClient对象
ftpClient = new FTPClient();
//2.连接FTP服务器
// 如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器
ftpClient.connect(hostname, port); //链接到ftp服务器
// System.out.println("连接到ftp服务器地址 --> ftp://" + hostName + ":" + port + " 成功..开始登录");
//3.判断连接ftp服务器是否成功
int reply = ftpClient.getReplyCode();
// System.out.println("以2开头的返回值就会为真:" + reply);
//以2开头的返回值就会为真
if (!FTPReply.isPositiveCompletion(reply)) {
ftpClient.disconnect();
return null;
}
//4.登录FTP服务器.用户名 密码
ftpClient.login(username, password);
System.out.println("登录成功." );
return ftpClient;
} catch (Exception e) {
e.printStackTrace();
ftpClient = null;
return ftpClient;
}
}
/**
* 向FTP服务器上传文件
* @param filePathName 上传文件的全路径名称
* @return 成功返回true,否则返回false
*/
public boolean uploadFile(String filePathName) {
// 初始表示上传失败
boolean success = false;
try {
// 创建FTPClient对象
ftpClient = connectFTPServer();
//创建文件夹
boolean flag = ftpClient.makeDirectory(remoteDir);
if(flag) {
System.out.println("创建文件夹:" + remoteDir );
}
// 转到指定上传目录
boolean flag0 = ftpClient.changeWorkingDirectory(remoteDir);
// 将上传文件存储到指定目录
if(filePathName == null || filePathName.length() == 0){
return success;
}
String filename = filePathName.substring(filePathName.replace("\\", "/").lastIndexOf("/") + 1, filePathName.length());
InputStream input = new FileInputStream(new File(filePathName));
// ftpClient.setBufferSize(1024);
// ftpClient.setControlEncoding("GBK");
// ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);//设置文件类型
boolean flag1 = ftpClient.storeFile(filename, input);
System.out.println("转到指定上传目录:" + flag0 + " 将上传文件存储到指定目录:" + flag1);
input.close(); // 关闭输入流
ftpClient.logout(); // 退出ftp
success = true; // 表示上传成功
} catch (Exception e) {
e.printStackTrace();
} finally {
if (ftpClient.isConnected()) {
try {
ftpClient.disconnect();
} catch (IOException ioe) {
}
}
}
return success;
}
/**
* 从FTP服务器指定目录下载文件 到本地目录中 OK
* @param fileName 要下载的文件名
* @param localPath 下载后保存到本地的路径
* @param showlist 下载时是否显示列表 ( true 显示 )
* @return
*/
public boolean downFile(String fileName, String localPath, boolean showlist) {
// 初始表示下载失败
boolean success = false;
if(fileName == null || fileName.length() == 0 || localPath == null || localPath.length() == 0){
return success;
}
try {
File file = new File(localPath);
if(!file.isDirectory()){
file.mkdir();
}
// 创建FTPClient对象
ftpClient = connectFTPServer();
// 转到指定下载目录
boolean flag = ftpClient.changeWorkingDirectory(remoteDir);
if(!flag) {
System.out.println("目录:" + remoteDir +"不存在!");
return success;
}
// 列出该目录下所有文件
FTPFile[] remoteFiles = ftpClient.listFiles();
// 遍历所有文件,找到指定的文件
if(showlist){
System.out.println("目录" + remoteDir + "下的文件:");
}
for (FTPFile ftpFile : remoteFiles) {
String name = ftpFile.getName();
if(showlist){
long length = ftpFile.getSize();
String readableLength = FileUtils.byteCountToDisplaySize(length);
System.out.println(name + ":\t\t" + readableLength);
}
if (name.equals(fileName)) {
// 根据绝对路径初始化文件
File localFile = new File(localPath + "/" + name);
// 输出流
OutputStream is = new FileOutputStream(localFile);
// 下载文件
ftpClient.retrieveFile(name, is);
is.close();
}
}
// 退出ftp
ftpClient.logout();
// 下载成功
success = true;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ftpClient.isConnected()) {
try {
ftpClient.disconnect();
} catch (IOException ioe) {
}
}
}
return success;
}
/**
* 显示FTP服务器指定文件夹中的文件及大小 OK
* @return
*/
private boolean showFileList() {
// 初始表示失败
boolean success = false;
try {
ftpClient = connectFTPServer();
FTPFile[] remoteFiles = null;
// 转到指定下载目录
boolean flag = ftpClient.changeWorkingDirectory(remoteDir);
if(!flag) {
System.out.println("目录:" + remoteDir +"不存在!");
return success;
} else{
remoteFiles = ftpClient.listFiles(remoteDir);
System.out.println("目录" + remoteDir + "下的文件:");
}
if(remoteFiles != null) {
for(int i=0;i < remoteFiles.length; i++){
String name = remoteFiles[i].getName();
long length = remoteFiles[i].getSize();
String readableLength = FileUtils.byteCountToDisplaySize(length);
System.out.println(name + ":\t\t" + readableLength);
}
}
// 表示成功
success = true;
} catch (Exception e) {
e.printStackTrace();
} finally {
//使用IO包关闭流
IOUtils.closeQuietly(outSteam);
try {
ftpClient.disconnect();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
return success;
}
public static void main(String[] args) {
FTPUpload ftp = new FTPUpload();
ftp.uploadFile("c:////test////bgssp.jar");
}
}
❸ jsp将图片等文件上传到服务器根目录下,读取二进制流存入mysql怎么样实现
插入图片到数据库代码片段
private Connection conn = null;
private PreparedStatement pstmt = null;
private static final String sql = "INSERT INTO images_info(image_id,image_name,image_size,image_date,image_type,image_description,author,image_data)VALUES(null,?,?,now(),?,?,?,?)";
public boolean addPhoto(ImageVo imageVo) {
boolean flag = false;
try{
//将文件转换为流文件
InputStream photoStream = new FileInputStream(imageVo.getImageData());
//获取数据库连接
conn = ConnectionFactory.getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, imageVo.getImageName());
pstmt.setInt(2, imageVo.getImageSize());
pstmt.setString(3 , "jpg");//图片类型
pstmt.setString(4, imageVo.getDescription());
pstmt.setString(5, imageVo.getAuthor());
pstmt.setBinaryStream(6, photoStream, (int)imageVo.getImageData().length());
int row = pstmt.executeUpdate();
if(row == 1){
flag = true;
}
}catch(FileNotFoundException fe){
fe.printStackTrace();
}catch(SQLException e){
e.printStackTrace();
}finally{
if(null != pstmt){
try{pstmt.close();}
catch(SQLException e){
e.printStackTrace();
}
}
if(null != conn){
try{conn.close();}
catch(SQLException e){
e.printStackTrace();
}
}
}
return flag;
}
❹ jsp上传文件的问题
用JSP实现文件上传功能,参考如下:
UploadExample.jsp
<%@ page contentType="text/html;charset=gb2312"%>
<html>
<title><%= application.getServerInfo() %></title>
<body>
上传文件程序应用示例
<form action="doUpload.jsp" method="post" enctype="multipart/form-data">
<%-- 类型enctype用multipart/form-data,这样可以把文件中的数据作为流式数据上传,不管是什么文件类型,均可上传。--%>
请选择要上传的文件<input type="file" name="upfile" size="50">
<input type="submit" value="提交">
</form>
</body>
</html>
doUpload.jsp
<%@ page contentType="text/html; charset=GBK" %>
<%@ page import="java.io.*"%>
<%@ page import="java.util.*"%>
<%@ page import="javax.servlet.*"%>
<%@ page import="javax.servlet.http.*"%>
<html><head><title>upFile</title></head>
<body bgcolor="#ffffff">
<%
//定义上载文件的最大字节
int MAX_SIZE = 102400 * 102400;
// 创建根路径的保存变量
String rootPath;
//声明文件读入类
DataInputStream in = null;
FileOutputStream fileOut = null;
//取得客户端的网络地址
String remoteAddr = request.getRemoteAddr();
//获得服务器的名字
String serverName = request.getServerName();
//取得互联网程序的绝对地址
String realPath = request.getRealPath(serverName);
realPath = realPath.substring(0,realPath.lastIndexOf("\\"));
//创建文件的保存目录
rootPath = realPath + "\\upload\\";
//取得客户端上传的数据类型
String contentType = request.getContentType();
try{
if(contentType.indexOf("multipart/form-data") >= 0){
//读入上传的数据
in = new DataInputStream(request.getInputStream());
int formDataLength = request.getContentLength();
if(formDataLength > MAX_SIZE){
out.println("<P>上传的文件字节数不可以超过" + MAX_SIZE + "</p>");
return;
}
//保存上传文件的数据
byte dataBytes[] = new byte[formDataLength];
int byteRead = 0;
int totalBytesRead = 0;
//上传的数据保存在byte数组
while(totalBytesRead < formDataLength){
byteRead = in.read(dataBytes,totalBytesRead,formDataLength);
totalBytesRead += byteRead;
}
//根据byte数组创建字符串
String file = new String(dataBytes);
//out.println(file);
//取得上传的数据的文件名
String saveFile = file.substring(file.indexOf("filename=\"") + 10);
saveFile = saveFile.substring(0,saveFile.indexOf("\n"));
saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1,saveFile.indexOf("\""));
int lastIndex = contentType.lastIndexOf("=");
//取得数据的分隔字符串
String boundary = contentType.substring(lastIndex + 1,contentType.length());
//创建保存路径的文件名
String fileName = rootPath + saveFile;
//out.print(fileName);
int pos;
pos = file.indexOf("filename=\"");
pos = file.indexOf("\n",pos) + 1;
pos = file.indexOf("\n",pos) + 1;
pos = file.indexOf("\n",pos) + 1;
int boundaryLocation = file.indexOf(boundary,pos) - 4;
//out.println(boundaryLocation);
//取得文件数据的开始的位置
int startPos = ((file.substring(0,pos)).getBytes()).length;
//out.println(startPos);
//取得文件数据的结束的位置
int endPos = ((file.substring(0,boundaryLocation)).getBytes()).length;
//out.println(endPos);
//检查上载文件是否存在
File checkFile = new File(fileName);
if(checkFile.exists()){
out.println("<p>" + saveFile + "文件已经存在.</p>");
}
//检查上载文件的目录是否存在
File fileDir = new File(rootPath);
if(!fileDir.exists()){
fileDir.mkdirs();
}
//创建文件的写出类
fileOut = new FileOutputStream(fileName);
//保存文件的数据
fileOut.write(dataBytes,startPos,(endPos - startPos));
fileOut.close();
out.println(saveFile + "文件成功上载.</p>");
}else{
String content = request.getContentType();
out.println("<p>上传的数据类型不是multipart/form-data</p>");
}
}catch(Exception ex){
throw new ServletException(ex.getMessage());
}
%>
</body>
</html>
运行方法,将这两个JSP文件放在同一路径下,运行UploadExample.jsp即可。