文件名称:java通过js上传文件
文件大小:2KB
文件格式:JAVA
更新时间:2015-11-14 09:34:07
fileupload
简单的利用java与js实现文件上传
package com.fendou.myString;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class FileUpload extends HttpServlet {
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
boolean a=ServletFileUpload.isMultipartContent(request);
if(a){
FileItemFactory factory=new DiskFileItemFactory();
ServletFileUpload upload=new ServletFileUpload
(factory);
Iterator items;
try{
items=upload.parseRequest
(request).iterator();
while(items.hasNext()){
FileItem item=(FileItem)
items.next();
if(!item.isFormField()){
String name=item.getName
();
String
fileName=name.substring(name.lastIndexOf("\\")+1, name.length());
String
path=request.getRealPath("file")+File.pathSeparatorChar+fileName;
File uploadFile=new File
(path);
request.getSession
().setAttribute("file", uploadFile);
item.write(uploadFile);
response.setContentType
("text/html");
response.setCharacterEncoding("utf-8");
PrintWriter
out=response.getWriter();
// out.print("
上传的文件为:"+name+"
");
// out.print("保存在服务器上
的地址为:"+path+"");
}
}
}catch(Exception e){
e.printStackTrace();
}
}
response.sendRedirect("smartupload.jsp");
}
}