使用 servlet 将文件从服务器更新到客户端
我正在尝试编写一个servlet,它可以将文件从客户端上传到服务器,并将文件从服务器下载到客户端,从特定位置到特定位置。但有两个问题阻止了我: 1、客户端上传文件到服务器时,如何告诉服务器该文件存放在哪里? 2.(更重要的是)如何从服务器下载到客户端部分?
这是到目前为止的代码:
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Server extends Thread {
public static final int PORT = 3333;
public static final int BUFFER_SIZE = 100;
@Override
public void run() {
try {
ServerSocket serverSocket = new ServerSocket(PORT);
while (true) {
Socket s = serverSocket.accept();
saveFile(s);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void saveFile(Socket socket) throws Exception {
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
FileOutputStream fos = null;
byte [] buffer = new byte[BUFFER_SIZE];
Object o = ois.readObject();
if (o instanceof String) {
fos = new FileOutputStream(o.toString());
} else {
throwException(null);
}
Integer bytesRead = 0;
do {
o = ois.readObject();
if (!(o instanceof Integer)) {
throwException(null);
}
bytesRead = (Integer)o;
o = ois.readObject();
if (!(o instanceof byte[])) {
throwException(null);
}
buffer = (byte[]) o;
fos.write(buffer, 0, bytesRead);
} while (bytesRead == BUFFER_SIZE);
fos.close();
ois.close();
oos.close();
}
public static void throwException(String message) throws Exception {
throw new Exception(message);
}
public static void main(String[] args) {
new Server().start();
}
}
package com.filetransfer.web;
import java.io.*;
import java.net.Socket;
import java.util.Arrays;
import javax.servlet.*;
import javax.servlet.http.*;
public class FileTransfer extends HttpServlet {
private static final long serialVersionUID = 1L;
public static final int PORT = 3333;
public static final int BUFFER_SIZE = 100;
public static final String HOST = "localhost";
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String action = request.getParameter("option");
System.out.println(action);
if ("upload".equals(action)) {
uploadFile(request);
} else if ("download".equals(action)) {
downloadFile(request, response);
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
public void reportError(HttpServletResponse response, String message) throws IOException {
response.sendError(HttpServletResponse.SC_NOT_FOUND, message);
}
public void uploadFile(HttpServletRequest request) {
String fileLocation = request.getParameter("localfile");
File file = new File(fileLocation);
Socket socket;
try {
socket = new Socket(HOST, PORT);
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
oos.writeObject(file.getName());
FileInputStream fis = new FileInputStream(file);
byte [] buffer = new byte[BUFFER_SIZE];
Integer bytesRead = 0;
while ((bytesRead = fis.read(buffer)) > 0) {
oos.writeObject(bytesRead);
oos.writeObject(Arrays.copyOf(buffer, buffer.length));
}
oos.close();
ois.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public void downloadFile(HttpServletRequest request, HttpServletResponse response) {
File file = new File(request.getParameter("remotefile"));
Socket socket;
InputStream inputStream = null;
OutputStream outputStream = null;
try {
socket = new Socket(HOST, PORT);
response.setContentLength((int)file.length());
outputStream = response.getOutputStream();
inputStream = new BufferedInputStream(new FileInputStream(file));
int nextByte;
while ((nextByte = inputStream.read()) != -1) {
outputStream.write(nextByte);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
I'm trying to write a servlet, that can upload a file from client to server and download a file from server to client from specific location to specific location. But two problems stopped me:
1. When uploading a file from client to server, how to tell to the server where to store the file?
2. (and more important) How to do the downloading from server to client part?
Here is the code so far:
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Server extends Thread {
public static final int PORT = 3333;
public static final int BUFFER_SIZE = 100;
@Override
public void run() {
try {
ServerSocket serverSocket = new ServerSocket(PORT);
while (true) {
Socket s = serverSocket.accept();
saveFile(s);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void saveFile(Socket socket) throws Exception {
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
FileOutputStream fos = null;
byte [] buffer = new byte[BUFFER_SIZE];
Object o = ois.readObject();
if (o instanceof String) {
fos = new FileOutputStream(o.toString());
} else {
throwException(null);
}
Integer bytesRead = 0;
do {
o = ois.readObject();
if (!(o instanceof Integer)) {
throwException(null);
}
bytesRead = (Integer)o;
o = ois.readObject();
if (!(o instanceof byte[])) {
throwException(null);
}
buffer = (byte[]) o;
fos.write(buffer, 0, bytesRead);
} while (bytesRead == BUFFER_SIZE);
fos.close();
ois.close();
oos.close();
}
public static void throwException(String message) throws Exception {
throw new Exception(message);
}
public static void main(String[] args) {
new Server().start();
}
}
package com.filetransfer.web;
import java.io.*;
import java.net.Socket;
import java.util.Arrays;
import javax.servlet.*;
import javax.servlet.http.*;
public class FileTransfer extends HttpServlet {
private static final long serialVersionUID = 1L;
public static final int PORT = 3333;
public static final int BUFFER_SIZE = 100;
public static final String HOST = "localhost";
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String action = request.getParameter("option");
System.out.println(action);
if ("upload".equals(action)) {
uploadFile(request);
} else if ("download".equals(action)) {
downloadFile(request, response);
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
public void reportError(HttpServletResponse response, String message) throws IOException {
response.sendError(HttpServletResponse.SC_NOT_FOUND, message);
}
public void uploadFile(HttpServletRequest request) {
String fileLocation = request.getParameter("localfile");
File file = new File(fileLocation);
Socket socket;
try {
socket = new Socket(HOST, PORT);
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
oos.writeObject(file.getName());
FileInputStream fis = new FileInputStream(file);
byte [] buffer = new byte[BUFFER_SIZE];
Integer bytesRead = 0;
while ((bytesRead = fis.read(buffer)) > 0) {
oos.writeObject(bytesRead);
oos.writeObject(Arrays.copyOf(buffer, buffer.length));
}
oos.close();
ois.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public void downloadFile(HttpServletRequest request, HttpServletResponse response) {
File file = new File(request.getParameter("remotefile"));
Socket socket;
InputStream inputStream = null;
OutputStream outputStream = null;
try {
socket = new Socket(HOST, PORT);
response.setContentLength((int)file.length());
outputStream = response.getOutputStream();
inputStream = new BufferedInputStream(new FileInputStream(file));
int nextByte;
while ((nextByte = inputStream.read()) != -1) {
outputStream.write(nextByte);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于您使用的是 HTTP servlet,因此我强烈建议使用 HTTP 客户端。不要传递专有的和自行发明的请求/响应格式,而只是根据 HTTP 协议构造请求和响应。当您遵守特定的传输标准时,毫无疑问有多种 API 和工具可以帮助您简化工作。
在客户端,您可以使用
java .net.URLConnection
或 Apache HttpClient 为此。通过 HTTP 从客户端向服务器发送文件(上传)通常需要multipart/form-data
请求编码。通过 HTTP 从服务器向客户端发送文件(下载)通常只需要正确的Content-Type
标头和整个文件作为响应正文。在这个答案的底部 您可以找到如何通过
URLConnection
上传文件的示例(以及在 这个答案是 Apache HttpClient 4 的示例)。在这个答案中,您可以找到一个示例如何在servlet中处理上传的文件。保存上传的文件很简单:只需将获得的InputStream
写入某个FileOutputStream
即可。在本文中,您可以找到如何发送文件以供下载的示例。保存下载的文件也很容易,只需将URLConnection#getInputStream()
写入某个FileOutputStream
即可。Since you're using a HTTP servlet, I strongly suggest to use a HTTP client. Don't pass around proprietary and self-invented request/response formats around, but just construct requests and responses according the HTTP protocol. When you adhere a certain transport standard, then there is no doubt that there are several API's and tools available which may ease the job.
In the client side, you can use
java.net.URLConnection
or Apache HttpClient for this. Sending files over HTTP from client to server (uploading) usually require amultipart/form-data
request encoding. Sending files over HTTP from server to client (downloading) usually require just a correctContent-Type
header and the entire file as response body.At the bottom of this answer you can find an example how to upload files by
URLConnection
(and in this answer an example with Apache HttpClient 4). In this answer you can find an example how to process the uploaded file in servlet. Saving the uploaded file is easy: just write the obtainedInputStream
to someFileOutputStream
. In this article you can find an example how to send the file for download. Saving the downloaded file is also easy, just writeURLConnection#getInputStream()
to someFileOutputStream
.