我正在尝试使用servlet从jsp页面上传图像。但我怎么能得到我的文件 来自jsp文件的servlet。
答案 0 :(得分:2)
答案 1 :(得分:1)
这是我的代码可以帮助你.... :)
您可以使用此代码上传任何类型的图片,pdf,txt。
import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
@SuppressWarnings("deprecation")
public class Upload extends HttpServlet
{
/**
*
*/
private static final long serialVersionUID = 1L;
public void doPost(HttpServletRequest request,HttpServletResponse response) throws IOException,ServletException
{
System.out.println("inside upload.jsp");
String filename="";
//String login=session.getAttribute("studuser").toString();
DiskFileUpload files=new DiskFileUpload();
@SuppressWarnings("rawtypes")
List list=null;
try {
list = files.parseRequest(request);
} catch (FileUploadException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
@SuppressWarnings("rawtypes")
Iterator itr=list.iterator();
System.out.println("before while......");
DBManager db=new DBManager();
db.getConnect();
@SuppressWarnings("unused")
Connection con1=(Connection) db.con;
while(itr.hasNext())
{
FileItem file=(FileItem)itr.next();
filename=file.getName();
System.out.println("**********"+filename);
if(filename!=null)
{
int index=filename.lastIndexOf("/");
filename=filename.substring(index+1);
//System.out.println( application.getRealPath(""));
File fNew=new File("F:/worksapce/Data-s/"+filename);
try
{
file.write(fNew);
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("after upload");
}
}
response.sendRedirect("upload_success.jsp");
}
}