
客户端代码如下:
import java.io.DataOutputStreamimport java.io.File
import java.io.FileInputStream
import java.io.IOException
import java.net.InetSocketAddress
import java.net.Socket
/**
* 文件发送客户端主程序
* @author admin_Hzw
*
*/
public class BxClient {
/**
* 程序main方法
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
int length = 0
double sumL = 0
byte[] sendBytes = null
Socket socket = null
DataOutputStream dos = null
FileInputStream fis = null
boolean bool = false
枯拦 try {
File file = new File("D:/天啊.zip") //要传输的文件路径
long l = file.length()
socket = new Socket()
socket.connect(new InetSocketAddress("127.0.0.1", 48123))
dos = new DataOutputStream(socket.getOutputStream())
fis = new FileInputStream(file)
sendBytes = new byte[1024]
while ((length = fis.read(sendBytes, 0, sendBytes.length)) > 0) {
sumL += length
System.out.println("已传输:"+((sumL/l)*100)+"%")
dos.write(sendBytes, 0, length)
dos.flush()
}
//虽然数据类型不同,但JAVA会自动转换成相同数据类型后在做比较
if(sumL==l){
bool = true
}
}catch (Exception e) {
System.out.println("客户端文件传输异常")
bool = false
e.printStackTrace()
} finally{
if (dos != null)
dos.close()
没此胡 if (fis != null)
fis.close()
if (socket != null)
socket.close()
}
System.out.println(bool?"成功":"失败")
}
}
服务端代码如下:
import java.io.DataInputStreamimport java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.net.ServerSocket
import java.net.Socket
import java.util.Random
import com.boxun.util.GetDate
/**
* 接收文件服务
* @author admin_Hzw
*
*/
public class BxServerSocket {
/**
* 工程main方法
* @param args
*/
public static void main(String[] args) {
try {
final ServerSocket server = new ServerSocket(48123)
Thread th = new Thread(new Runnable() {
扒知public void run() {
while (true) {
try {
System.out.println("开始监听...")
/*
* 如果没有访问它会自动等待
*/
Socket socket = server.accept()
System.out.println("有链接")
receiveFile(socket)
} catch (Exception e) {
System.out.println("服务器异常")
e.printStackTrace()
}
}
}
})
th.run() //启动线程运行
} catch (Exception e) {
e.printStackTrace()
}
}
public void run() {
}
/**
* 接收文件方法
* @param socket
* @throws IOException
*/
public static void receiveFile(Socket socket) throws IOException {
byte[] inputByte = null
int length = 0
DataInputStream dis = null
FileOutputStream fos = null
String filePath = "D:/temp/"+GetDate.getDate()+"SJ"+new Random().nextInt(10000)+".zip"
try {
try {
dis = new DataInputStream(socket.getInputStream())
File f = new File("D:/temp")
if(!f.exists()){
f.mkdir()
}
/*
* 文件存储位置
*/
fos = new FileOutputStream(new File(filePath))
inputByte = new byte[1024]
System.out.println("开始接收数据...")
while ((length = dis.read(inputByte, 0, inputByte.length)) > 0) {
fos.write(inputByte, 0, length)
fos.flush()
}
System.out.println("完成接收:"+filePath)
} finally {
if (fos != null)
fos.close()
if (dis != null)
dis.close()
if (socket != null)
socket.close()
}
} catch (Exception e) {
e.printStackTrace()
}
}
}
common-fileupload是jakarta项目组开发纳敏轿的一个功能很强大的上传文件组件下面先介绍上传文件到服务器(多文件上传):
import javax.servlet.*
import javax.servlet.http.*
import java.io.*
import java.util.*
import java.util.regex.*
import org.apache.commons.fileupload.*
public class upload extends HttpServlet {
private static final String CONTENT_TYPE = "text/htmlcharset=GB2312"
//Process the HTTP Post request
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType(CONTENT_TYPE)
PrintWriter out=response.getWriter()
try {
DiskFileUpload fu = new DiskFileUpload()
// 设置拿禅允许用户上传洞肆文件大小,单位:字节,这里设为2m
fu.setSizeMax(2*1024*1024)
// 设置最多只允许在内存中存储的数据,单位:字节
fu.setSizeThreshold(4096)
// 设置一旦文件大小超过getSizeThreshold()的值时数据存放在硬盘的目录
fu.setRepositoryPath("c://windows//temp")
//开始读取上传信息
List fileItems = fu.parseRequest(request)
// 依次处理每个上传的文件
Iterator iter = fileItems.iterator()
//正则匹配,过滤路径取文件名
String regExp=".+////(.+)$"
//过滤掉的文件类型
String[] errorType={".exe",".com",".cgi",".asp"}
Pattern p = Pattern.compile(regExp)
while (iter.hasNext()) {
FileItem item = (FileItem)iter.next()
//忽略其他不是文件域的所有表单信息
if (!item.isFormField()) {
String name = item.getName()
long size = item.getSize()
if((name==null||name.equals("")) &&size==0)
continue
Matcher m = p.matcher(name)
boolean result = m.find()
if (result){
for (int temp=0temp<ERRORTYPE.LENGTHTEMP++){
if (m.group(1).endsWith(errorType[temp])){
throw new IOException(name+": wrong type")
}
}
try{
//保存上传的文件到指定的目录
//在下文中上传文件至数据库时,将对这里改写
item.write(new File("d://" + m.group(1)))
out.print(name+" "+size+"")
}
catch(Exception e){
out.println(e)
}
}
else
{
throw new IOException("fail to upload")
}
}
}
}
catch (IOException e){
out.println(e)
}
catch (FileUploadException e){
out.println(e)
}
}
}
现在介绍上传文件到服务器,下面只写出相关代码:
以sql2000为例,表结构如下:
字段名:namefilecode
类型: varchar image
数据库插入代码为:PreparedStatement pstmt=conn.prepareStatement("insert into test values(?,?)")
代码如下:
。。。。。。
try{
这段代码如果不去掉,将一同写入到服务器中
//item.write(new File("d://" + m.group(1)))
int byteread=0
//读取输入流,也就是上传的文件内容
InputStream inStream=item.getInputStream()
pstmt.setString(1,m.group(1))
pstmt.setBinaryStream(2,inStream,(int)size)
pstmt.executeUpdate()
inStream.close()
out.println(name+" "+size+" ")
}
。。。。。。
这样就实现了上传文件至数据库
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)