日期:2014-05-20  浏览次数:20736 次

struts 2 文件上传 判断是否上传文件
各路大神,我想用struts 2 上传一个图片,但是,我不确定用户是否有上传。(就是他上传也可以,不上传也可以。)跪求你们给点帮助。
下面是action 代码
package action;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import dao.Newsdao;
import daoimpl.NewsdaoImpl;
import org.apache.struts2.ServletActionContext;

public class Inputnews 
{
  private String newstitle;
  private String newsindex;
  private File picture;
  private String pictureFileName;
   
  public String execute() throws Exception
  {
  String url = new String();
  File saved = new File(ServletActionContext.getServletContext().getRealPath("newsupload"),pictureFileName);
  InputStream ins = null;
  OutputStream ous = null;
  try
  {
  saved.getParentFile().mkdirs();
   
   
  ins = new FileInputStream(picture);
  ous = new FileOutputStream(saved);
 
  byte[] b = new byte[1024];
  int len = 0;
  while((len = ins.read(b)) != -1)
  {
  ous.write(b,0, len);
  }
  url = "newsupload" + pictureFileName;
   
  }catch(Exception e)
  {
  e.printStackTrace();
  }
  finally
  {
  if(ous != null) ous.close();
  if(ins != null) ins.close();
  }
   
   
  Newsdao newsdao = new NewsdaoImpl();
  newsdao.inputnews(newstitle, newsindex, url);
  return null;
  }
   
  public String getPictureFileName()
  {
  return this.pictureFileName;
  }
  public void setPictureFileName(String pictureFileName)
  {
  this.pictureFileName = pictureFileName;
  }
   
  public File getPicture()
  {
  return this.picture;
  }
  public void setPicture(File picture)
  {
  this.picture = picture;
  }
   
  public String getNewstitle()
  {
  return this.newstitle;
  }
  public void setNewstitle(String newstitle)
  {
  this.newstitle = newstitle;
  }
   
  public String getNewsindex()
  {
  return this.newsindex;
  }
  public void setNewsindex(String newsindex)
  {
  this.newsindex = newsindex;
  }
}
跪求帮忙。就是想知道判断他有没有上传图片的语句是怎么写的?

------解决方案--------------------
public class upload {


public void fileload(File img,String imgFileName) throws IOException {

InputStream is = new FileInputStream(img);

String path = ServletActionContext.getRequest().getRealPath("/img");

File file = new File(path,imgFileName);

OutputStream os = new FileOutputStream(file);

byte[] buffer = new byte[1024];

int length = 0;

while((length=is.read(buffer))>0) {
os.write(buffer, 0, length);
}
is.close();
os.close();

}

}
这是我用的文件上传类,在action调用这个类就可以了,这样用户不上传图片也没什么问题了,用户不上传图片的时候可以给他一个默认值
------解决方案--------------------