我本地有若干文件,知道服务器的IP和端口,就是说可以连接服务器的servlet,用HttpUrlConnection和URL这种方式,怎么把这个图片保存到服务器上。  说明:
1、已知本地的文件路径
2、需要根据本地文件的类型,在服务器上保存到不同的文件夹,而且服务器的文件夹之前并没有创建,需要连接的时候再创建请高手指点。已经做了快2天了。崩溃了快。如果我把服务器设置到本机,测试通过。    但是换一个服务器就不行。
代码如下:本地代码如下
String urlfn = null;
// 从资源文件中读出服务器的URL
Properties prop = new Properties();
prop = CommonFun.readProperty("config.properties");
String LRMIP = prop.getProperty("ip");
String LRMPort = prop.getProperty("port");
String LRMContext = prop.getProperty("content"); HttpURLConnection conn = null;
InputStream is = null;
DataOutputStream dos = null;
// 拼出服务器的URL,然后访问
if (LRMIP != null && LRMPort != null && LRMContext != null) {
urlfn = "http://" + LRMIP + ":" + LRMPort + "/" + LRMContext
+ "/servlet/GetImage?"
+ Base64.encode("date=" + CommonFun.formatDate(false, new Date()) + "&fileName=" + sourcePath + File.separator + sourceFileName); try {
conn = CommonFun.getURLConnection(urlfn);
conn.connect();
is = conn.getInputStream();

dos = new DataOutputStream(new FileOutputStream(filePath
+ File.separator + sourceFileName));
byte[] b = new byte[1024];
while (is.read(b) != -1) {
dos.write(b);// 写入指定文件
}
dos.flush();
dos.close();
is.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
这是服务器端Servlet的内容
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String url = Base64.decode(request.getQueryString());
String file_name = url.split("=")[2];
if(file_name != null){
String imageLocation = file_name.replace("|",File.separator);
Constants.BusinessLog.info("fileName="+file_name.replace("|", File.separator));
File file = null;
ServletOutputStream out = response.getOutputStream();
FileInputStream in = null;
try {
file = new File(imageLocation); in = new FileInputStream(file);
String fileName = file.getName();
String miniType = fileName.substring(fileName.indexOf('.') + 1);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte b[] = new byte[1024];
while (true) {
int bytes = in.read(b);
if (bytes == -1) {
break;
}
baos.write(b, 0, bytes);
}
in.close();
b = baos.toByteArray();
response.setContentType(getMiniType(miniType));
response.setContentLength(b.length);
out.write(b, 0, b.length);
out.flush();
out.close();
} catch (Exception e) {
Constants.ExceptionLog.error("文件找不到 文件名为: " + file.getAbsolutePath());
response.getOutputStream().write("File not found!Please check URL!".getBytes());
}

}else{
response.getOutputStream().write("FileName is null".getBytes());
}
}