How to Upload url (http files) using Java to my web server?
I'm trying make a several uploads to my web server. I want to upload files that are at a specific web site, like all *.jpg files, so I started trying. this kind of code, using FTP, URL and Object File.
UploaderDownloader up = new UploaderDownloader();
URL url = new URL("http://i1.nyt.com/images/2011/05/22/magazine/22moth_cover/22moth_cover-moth.jpg");
File file = new File(url.getFile());
up.upload("127.0.0.1", "USER", "PASSWORD", "/testeUploader/132.jpg",file);
but this doesn't work for me. So, I'm looking to discover how implement this using the best choices. upload a url file that isn't at my PC to a web se开发者_StackOverflow社区rver.
If I understand you right, you want to download a file from a HTTP server and then upload it to a FTP server. In that case you do not need the File
object at all. It's only useful if you want to save it to the local disk file system, but you seem to not need this. All you need to do is to get an InputStream
of the file from the HTTP server and then send it to the FTP server.
Here's a kickoff example how to get the file from the HTTP server in flavor of an InputStream
.
InputStream input = new URL("http://example.com/image.jpg").openStream();
Simple isn't it? Please ensure that you respect the robots.txt
of the site in question, or you might get IP-banned.
As to FTP'ing, the basic Java SE doesn't offer any useful API's for this and I have no idea what FTP client you're using since your question only contains homegrown and undocumented code, so here's just an example with Apache Commons Net FTPClient:
FTPClient ftp = new FTPClient();
ftp.connect("ftp.example.com");
ftp.login("username", "password");
ftp.storeFile("image.jpg", input); // <-- Here, it's just InputStream.
ftp.logout();
That's it.
Where is the source for UploaderDownloader
? Typically you can not perform a file upload of a file that is not at your PC without first downloading the file to your PC and then uploading it to the destination server.
It is possible using some FTP setups to do server-to-server transfers, or using one of the other available file transfer solutions like Dropbox or box.net, but generally what you're trying to do involves a local download first and then a file upload. For HTTP downloads and uploads Apache HttpClient is generally the library of choice: see How can I make a multipart/form-data POST request using Java? on the upload part, and http://hc.apache.org/httpcomponents-client-ga/tutorial/html/ for a general tutorial.
精彩评论