我是一个新的java。我知道的不多。我只是学习java。我正在开发一个网络应用程序。其中我有一个选项下载图像。如果用户点击他应该能够下载图像从服务器到客户端说在位置c://。
我已经实现了这个代码::
import java.awt.Image;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import javax.imageio.ImageIO;
public class DownloadingImages{
public DownloadingImages() {}
public void download(String name) throws MalformedURLException, IOException{
Image image = null;
try {
//URL url = new URL("file:///E:/myproject/build/web/images/Webcam.jpg");
String spath="http://localhost:5051/marketpoint/images/";
String cpath="C:\\";
spath = spath + name ;
cpath = cpath + name ;
System.out.println("FULL path::: "+spath);
URL url = new URL(spath);
InputStream in = new BufferedInputStream(url.openStream());
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int n = 0;
while (-1!=(n=in.read(buf)))
{
out.write(buf, 0, n);
}
out.close();
in.close();
byte[] response = out.toByteArray();
FileOutputStream fos = new FileOutputStream(cpath);
fos.write(response);
fos.close();
} catch (IOException e) {
}
}
}
Here
name = name of image thta client wants to download.
这里的问题是,图像下载到服务器端。在c://。有人能告诉我哪里出错了吗?
为此,我使用网络bean作为我的编辑器,Apache Tomcat作为服务器。客户端和服务器都通过5051端口连接。客户端要从服务器下载的图像是简单的jpg图像。有人能帮我解决这个问题吗?
3条答案
按热度按时间xdnvmnnf1#
如果文件被下载到C:\,那么当你打开
FileOutputStream
时,你的cpath
变量就等于这个值。这意味着你的name
变量是作为一个空字符串传入的。试着加入一些日志记录语句(或者更好,使用netbeans调试器!),看看当你的代码执行时,你的变量持有什么值。编辑:我想我现在明白问题所在了。您将其作为servlet或类似的东西运行。这意味着您的代码是在服务器上执行的,而不是在客户机上执行的。如果您想将文件下载到客户机上的特定路径,则必须使用
Applet
或类似的在客户机端运行的东西。或者,你可以在HTTP响应中返回这个文件,用户的浏览器会询问他们把文件保存在哪里,不过,那时,用户可以自己在浏览器中导航到这个jpg文件。如果这不能回答您的问题,您可能需要更详细地解释您的用例。
dvtswwa32#
试试这个运行代码。它会帮助你的。
u91tlkcl3#
请先试用此代码: