上传图片图片服务器
package cms.huisou.common.util;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import org.apache.struts2.ServletActionContext;
import cms.huisou.common.struts2.action.BaseAction;
import com.opensymphony.xwork2.ActionSupport; /**
* 保证有commons-fileupload.jar,Commons-io.jar,注意jsp传过来的File的name= imgFile ,配置文件加上 interceptor-ref name= fileUploadStack /interceptor-ref
* 包含上传的只需要继承FileUploadAction,自定义一个方法,使用FileUploadAction属性操作上传,例子cms.huisou.info.action.AddHcinfoAct的upload,需要上传的时候只需要this.upload();
*/
public class FileUploadAction extends BaseAction {
org.apache.struts2.dispatcher.multipart.JakartaMultiPartRequest f;
protected static final int BUFFER_SIZE = 16 * 1024;
protected File imgFile;
protected String imgFileContentType;
protected String imgFileFileName;
public File getImgFile() {
return imgFile;
}
public void setImgFile(File imgFile) {
this.imgFile = imgFile;
}
public String getImgFileContentType() {
return imgFileContentType;
}
public void setImgFileContentType(String imgFileContentType) {
this.imgFileContentType = imgFileContentType;
}
public String getImgFileFileName() {
return imgFileFileName;
}
public void setImgFileFileName(String imgFileFileName) {
this.imgFileFileName = imgFileFileName;
}
protected static void copy(File src, File dst) {
try {
InputStream in = null ;
OutputStream out = null ;
try {
in = new BufferedInputStream( new FileInputStream(src),
BUFFER_SIZE);
out = new BufferedOutputStream( new FileOutputStream(dst),
BUFFER_SIZE);
byte [] buffer = new byte [BUFFER_SIZE];
while (in.read(buffer) 0 ) {
out.write(buffer);
}
} finally {
if ( null != in) {
in.close();
}
if ( null != out) {
out.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
protected static String getExtention(String fileName) {
int pos = fileName.lastIndexOf( . );
return fileName.substring(pos);
}
}
class AddHcinfoAct extends FileUploadAction 代码写道
public void upload() {
imgFileFileName = new Date().getTime()+ getExtention(imgFileFileName);
File imageFile = new
File(ServletActionContext.getServletContext().getRealPath( /UploadImages )+ / +
imgFileFileName);
copy(imgFile, imageFile);
}
注意JSP提交的时候加上:
enctype= multipart/form-data
然后在相应的方法调用this.upload()即可
好一段时间因为时间忙,偶尔光顾下javaeye。
我记得以前做过用htmlparser抓取的img标签,然后要把所有的图片上传到图片服务器上,这期间经历了好多的波折,刚开始直接写流,不行,因为想javaeye,百度等有的图片路径是非正常路径的。比如:www.javaeye/upload/test.jpg2005-1-1/ 这显示的是一个图片,但是我写流就出现了问题,而且对百度的图片不能抓取。第二次改进
,用百度爬虫写流,但是我不知道为何,到上传到服务器后图片变形了。这种方案不行,后来用了httpclient,当我试啦试百度和javaeye后,很惊喜,都可以,后来测试了很多的非正常的图片,也未发现有不行的情况存在。
1: 普通的地址图片上传,只能上传普通的地址一般是后缀jpg,png,gif之类的图片。其中imgurl是图片地址路径,disppath为保存的文件夹,name是文件名
URL u = new URL(imgurl);
URLConnection uc = u.openConnection(); InputStream in = uc.getInputStream(); OutputStream out = new FileOutputStream(disppath+ name);
byte[] buffer = new byte[1024]; while (in.read(buffer) 0) {
out.write(buffer);
}
out.flush();
out.close();
in.close();
2: 可以上传特殊的图片,后缀可以是/180,/order等等特殊图片路径的
public void readFileAndWrite(String Stringurl,String targetPath) {
try {
System.getProperties();
URL url = new URL(Stringurl);
URLConnection urlconnection = url.openConnection();
urlconnection.setDoInput(true);
urlconnection.setDoOutput(true);
urlconnection.setUseCaches(false);
urlconnection.setRequestProperty( User-Agent ,
Baiduspider+(+) );
urlconnection.setRequestProperty( Content-Type ,
application/x-www-form-urlencoded );
InputStream input = urlconnection.getInputStream();
File dest = new File(targetPath);
FileOutputStream out = new FileOutputStream(dest);
int b = 0;
while((b= input.read())!=-1)
out.write(b);
out.close();
input.close();
} catch (Exception u8e) {
log.error(u8e.getMessage());
throw new RuntimeException(u8e.getMessage());
}
}
3: 上面两种可能方,案都不能上传这样的图片百度很特殊的图片,百度图片屏蔽啦一些不
法的读取文件,下面是模拟客户端来抓取图片,上传需要三个jar包:httpcore-4.0.1.jar,
httpclient-4.0.jar,commons-logging-1.1.1.jar,代码实例:
HttpClient httpclient = new DefaultHttpClient(); String url = ; // 生成一个请求对象
HttpGet httpget = new HttpGet(url);
httpget.setHeader( referer , ); // 执行请求
HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream in = entity.getContent();
int b = 0;
FileOutputStream out = new FileOutputStream( a.jpg );
while ((b = in.read()) != -1) {
System.out.println(b);
out.write(b);
}
out.close();
in.close();
}
httpclient.getConnectionManager().shutdown(); 部分代码: // htmlparser抓取图片
public static String parserto(String contentString,String pathString,String
httpurl) {
String stringBuffer=null;
Date date = new Date();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat( yyyyMMddhhmmssms );
try {
List list = new ArrayList();
Parser parser = Parser.createParser(contentString, UTF-8 );
NodeList nodeList = parser
.extractAllNodesThatMatch(new NodeFilter() {
public boolean accept(Node node) {
if (node instanceof ImageTag)// img 标记
return true;
return false;
}
});
if(nodeList.size() 0){
for (int i = 0; i nodeList.size(); i++) {
String url = ((ImageTag) nodeList.elementAt(i)).getImageURL();
url=StrUtils.htm2txt(url);
Random ran = new Random();
int a = ran.nextInt(1000);
String imgname = simpleDateFormat.format(new Date())+a+ .jpg ;
String reurl = ((ImageTag)
nodeList.elementAt(i)).getImageURL();
contentString=contentString.replace(reurl, httpurl + imgname);
// pathString = C:\\Documents and Settings\\Administrator\\桌面\\t\\ ;
writeimg(url,pathString+imgname);
}
}
} catch (Exception e) {
}
contentString.replaceAll( nbsp; , );
return contentString;
}
//httpclient模拟器写图片,几乎所有格式的图片都可以,ftp方式的图片? http !
public static void writeimg(String url,String targetPath) throws ClientProtocolException, IOException {
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
httpget.setHeader( referer , );
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream in = entity.getContent();
int b = 0;
FileOutputStream out = new FileOutputStream(new File(targetPath));
while ((b = in.read()) != -1) {
out.write(b);
}
out.close();
in.close();
}
httpclient.getConnectionManager().shutdown();
}
注意:htmlparser和httpclient需要添加相应的jar