首页 新闻 会员 周边 捐助

怎么把图片传到服务器上?

0
悬赏园豆:5 [待解决问题]

怎么把图片传到服务器上?给出代码谢谢。

沉默与否的主页 沉默与否 | 初学一级 | 园豆:190
提问于:2010-12-10 13:39
< >
分享
所有回答(2)
0

什么语言?asp.net?php?...

什么方式?普通?异步?

什么框架?js?jquyer?...

Astar | 园豆:40805 (高人七级) | 2010-12-11 13:14
0

这个得用fileupload.jar 

里面的代码能用到,这个是在图片里打水印的,然后上传至服务器的

public class FileuploadAction extends BaseAction{
 /**
  *
  */
 private static final long serialVersionUID = 8283321781117635350L;

 @SuppressWarnings("unchecked")
 public String execute() throws Exception {
  boolean isMultipart = ServletFileUpload.isMultipartContent(req);
  if(! isMultipart){
   req.setAttribute("error", "不是上载请求!");
   return "/fileupload.jsp"; 
  }
  // Create a factory for disk-based file items
  FileItemFactory factory = new DiskFileItemFactory();

  // Create a new file upload handler
  ServletFileUpload upload = new ServletFileUpload(factory);

  // Parse the request
  List<FileItem> /* FileItem */ items = upload.parseRequest(req);
  
  for (FileItem item : items) {
   if(item.isFormField()){
    //表单普通field
    req.setAttribute(item.getFieldName(), item.getString("utf-8"));
   }else{
    
    String photo = "/photo/" + System.currentTimeMillis() + "-" + item.getName();
    String filename = servlet.getServletContext().getRealPath(photo);
    
    BufferedImage img = ImageIO.read(item.getInputStream());
   // BufferedImage thumb = (BufferedImage)img.getScaledInstance(50, 50, BufferedImage.SCALE_SMOOTH);
    Image thumb = img.getSubimage(0, 0, 200, 200);
    BufferedImage bufImg =
     new BufferedImage(200,200,BufferedImage.TYPE_3BYTE_BGR);
    bufImg.getGraphics().drawImage(thumb, 0, 0, null);
    bufImg.getGraphics().setColor(new Color(255,255,255,230));
    bufImg.getGraphics().drawString("程亮版权所有", 10, 100);
    
    
    File dir =
     new File( servlet.getServletContext().getRealPath("/photo"));
    if(!dir.exists()){
     dir.mkdir();
    }
    
    File file = new File(filename);
    
    ImageIO.write(bufImg, "jpeg", file);
   // item.write(file);
    
    req.setAttribute(item.getFieldName(), photo);
    req.setAttribute("photoName", item.getName());
   }
  }
  return "/fileupload.jsp";
 }

cmcl111 | 园豆:205 (菜鸟二级) | 2010-12-13 00:18
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册