有一台专门的图片服务器 A,然后服务器B要满足上传、修改图片到服务器A上,需求大概就是这样。
解决途径采用 HttpClient 模拟from表单提交,在A上有一个 服务端来处理上传图片的请求
HttpClient用的是 4.23
测试成功 win7上传xp,win7上传linux(不知道版本)
参考:
http://www.cnblogs.com/zhangxz/archive/2010/09/06/1819333.html
1.服务端
主要方法
url:http://192.168.1.135:8080/servlet/UploadImageServlet?xx=xx&xx=xx
</pre><pre name="code" class="java">public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// init();
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
try
{
System.out.print("*********开始上传图片到服务器************");
// 获取url后面参数
String realPath = (String) request.getParameter("realPath");
String fileName = (String) request.getParameter("fileName");
String delOldPath = (String) request.getParameter("delOldPath");
System.out.println("fileName:"+fileName);
System.out.println("realPath:"+realPath);
System.out.println("delOldPath:"+delOldPath);
if(null != realPath && !"".equals(realPath)){
initPath(realPath);
}
DiskFileItemFactory factory = new DiskFileItemFactory();
// 设置缓冲区大小,这里是4kb
factory.setSizeThreshold(10240000);
// 设置缓冲区目录
factory.setRepository(tempPathFile);
ServletFileUpload upload = new ServletFileUpload(factory);
// 设置最大文件尺寸,这里是4MB
upload.setSizeMax(4194304);
upload.setHeaderEncoding("UTF-8");
// 得到所有的文件
List<FileItem> items = upload.parseRequest(request);
Iterator<FileItem> i = items.iterator();
while (i.hasNext()){
FileItem fi = (FileItem) i.next();
String filename = fi.getName();
if (filename != null && checkFormat(filename)){
File fullFile = new File(filename);
File savedFile = new File(uploadPath, fullFile.getName());
fi.write(savedFile);
System.out.print("----------------------"+fileName+",上传成功---------");
}else{
System.out.print("----------------------上传失败,"+fileName+":格式不对---------");
}
}
// 删除旧的图片
if(null!=delOldPath && !"".equals(delOldPath)){
delOldPic(delOldPath);
}
}
catch (Exception e){
System.out.println(e.getMessage());
e.printStackTrace();
}
}
其它方法:
// 创建路径
public void initPath(String path){
uploadPath = path;
tempPath = path+"/temp";
File uploadFile = new File(path);
if (!uploadFile.exists()) {
uploadFile.mkdirs();
}
File tempPathFile = new File(tempPath);
if (!tempPathFile.exists()) {
tempPathFile.mkdirs();
}
}
//上传格式检查
public boolean checkFormat(String fileName){
String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1);
String[] fileTypes = new String[] { "gif", "jpg", "jpeg", "png","bmp" };
//检查扩展名
if (!Arrays.<String> asList(fileTypes).contains(fileExt)) {
return false;
}
return true;
}
public String dealFileName(String fileName){
String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1);
// 名称后面加上时间戳
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
String uploadTime=simpleDateFormat.format(new Date()) + "_" + String.valueOf(System.currentTimeMillis());
StringBuilder newName = new StringBuilder(fileName.substring(0,fileName.lastIndexOf(".")));
newName.append("_").append(uploadTime).append(".").append(fileExt);
return newName.toString();
}
// 修改时,删除旧的图片
public void delOldPic(String oldPicPath){
if (null != oldPicPath && !"".equals(oldPicPath))
{
//http://img.114piaowu.com/upload/ask/20131119_1384843321562.jpg
String root = "/data/www/ImgServer/images/";
String tempPath = "";
if ( -1 != oldPicPath.lastIndexOf("/images"))
{
String[] names = oldPicPath.split("\\/");
String picName = names[names.length-1];
String dirPath = names[names.length-2];
tempPath = dirPath + "/" + picName;
System.out.print(dirPath+","+picName);
System.out.print(tempPath);
}
File file = new File(root + tempPath);
if (file.exists())
{
file.delete();
}
}
}
//重构上传图片的名称: 名称_日期时分秒_随机数.jpg
public void dealFileName(){
String fileExt = fileFileName.substring(fileFileName.lastIndexOf(".") + 1).toLowerCase(); //得到上传文件的扩展名
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
String newImgName = fileFileName.substring(0,fileFileName.lastIndexOf(".")) + "_" + df.format(new Date()) + "_"
+ new Random().nextInt(1000) + "." + fileExt;
fileFileName = newImgName;
}
2.客户端
主要方法
public String uploadFileDetail(File file,String fileName,String url,String realPath,String delOldPath) throws UnsupportedEncodingException{
// url = "http://192.168.1.135:8080/servlet/UploadImageServlet"; //本地url
// url = "http://192.168.1.136:8081/ImgServer/servlet/UploadImageServlet"; //windows系统其他机器url
url += "?realPath="+realPath+"&delOldPath="+URLEncoder.encode(delOldPath, "UTF-8")+"&fileName="+URLEncoder.encode(fileName, "UTF-8");
PostMethod postMethod = new PostMethodUTF8(url);
try {
HttpClient client = new HttpClient();
Part[] parts = {new ImagePart(fileName, file)};
HttpMethodParams params = new HttpMethodParams();
postMethod.setParams(params);
postMethod.setRequestEntity(new MultipartRequestEntity(parts,postMethod.getParams()));
client.getHttpConnectionManager().getParams().setConnectionTimeout(50000);//设置超时
int status = client.executeMethod(postMethod);
System.out.println("status:"+status);
if (status == HttpStatus.SC_OK){
System.out.println("客户端打印*********:上传成功");
return "success";
}else{
System.out.println("客户端打印*********:上传失败");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (HttpException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally{
postMethod.releaseConnection();
}
return "false";
}
其中注意点,
1.url后面传中文参数乱码
封装PostMethod类,设置url编码,并且 中文参数用URLEncoder.encode(xx, "UTF-8");转码,同样服务端接收时要设置编码
public class PostMethodUTF8 extends PostMethod {
public PostMethodUTF8(String url){
super(url);
}
@Override
public String getRequestCharSet() {
return "utf-8";
}
}
2.Part 类传参数时候中文也会乱码
封装FilePart类,我为了方便改变了其中一个参数
public class ImagePart extends FilePart {
// 上传图片到铁行服务器,中文乱码解决
private String fileName;// 真实的文件名称
public ImagePart(String name, File file) throws FileNotFoundException {
super(name, file);
this.fileName = name;
}
protected void sendDispositionHeader(OutputStream out) throws IOException {
super.sendDispositionHeader(out);
// String filename = getSource().getFileName();
String filename = fileName;
if (filename != null) {
out.write(EncodingUtil.getAsciiBytes(FILE_NAME));
out.write(QUOTE_BYTES);
out.write(EncodingUtil.getBytes(filename, "utf-8"));
out.write(QUOTE_BYTES);
}
}
}