求指教jsp用jspsmartupload组件上传文件技术
怎么实现文件上传
import
import
import
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.
import org.
import org.
import org.
import org.
public class UploadServlet extends HttpServlet {
public UploadServlet() {
super();
}
public void destroy() {
super.destroy();
}
public void execute(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//初始化servletfileupload对象,该对象提供了从表单中得到二进制数据的方法
ServletFileUpload file=new ServletFileUpload(new DiskFileItemFactory());
//包含多个文件
try {
List<FileItem>list=file.parseRequest(request);
//得到上传文件的请求
Iterator<FileItem> i=list.iterator();
//因为有多个文件所以把这些文件放到LIST集合中
while(i.hasNext()){
FileItem fileitem=(FileItem)i.next();
//对这个集合进行迭代
String filename=fileitem.getName();
System.out.println("文件的名字是"+filename);
if(fileitem.isFormField()){
//因为传过来的数据有的是表单数据,不是文件
//所以要判断
//isFormField()是判断文件是表单数据
String filename2=fileitem.getName();
String filevalue=fileitem.getString("GBK");
System.out.println(filename2+filevalue);
request.setAttribute("name",filevalue);
}
else{
//如果传来的是文件的话
String path=fileitem.getName();
System.out.println(path);
int count=path.lastIndexOf("\\");
//首先截取这个文件名
String name=path.substring(count+1);
//因为indexof是从0开始,所以要+1
try {
fileitem.write(new File("e:\\上传的文件"+name));
//将文件写到你要的路径即可
} catch (Exception e) {
e.printStackTrace();
}
}
}
} catch (FileUploadException e) {
e.printStackTrace();
}
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
execute(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
execute(request, response);
}
public void init() throws ServletException {
}
}
希望帮到你。