网页上传图片

来源:互联网 发布:海岛奇兵20级野人数据 编辑:程序博客网 时间:2024/04/29 10:13

网页中建立一个表单

<form action="/Blog/servlet/Shangchuan" method="post" enctype="multipart/form-data">
       <input type="file" name="image" class="img">
       <input type="submit" value="确认上传" class="blue">
        </form>‘

在servlet中进行处理

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.jspsmart.upload.File;
import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;

public class Shangchuan extends HttpServlet{
 private static final long serialVersionUID = 1L;
 public void doPost(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException{
  PrintWriter out=response.getWriter();
  SmartUpload smartupload=new SmartUpload();
  try{
  smartupload.initialize(this.getServletConfig(),request,response);
  smartupload.setAllowedFilesList("jpg,PNG,JPG");
  smartupload.upload();
  File file=smartupload.getFiles().getFile(0);
  file.saveAs("/Image/"+file.getFileName(),File.SAVEAS_VIRTUAL);
  out.print("上传成功");
  }
  catch(Exception e){
   out.print("上传失败,可能是图片格式错误,暂时只支持以jpg,JPG,PNG结尾的格式的图片");
  }
  
 }
 
}

0 0
原创粉丝点击