日期:2014-05-17  浏览次数:20725 次

fileupload文件上传
这是我的servlet
import javax.servlet.http.*;
import java.util.*;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.*;

public class upload extends HttpServlet {
private static final long serialVersionUID=1L;
File tempDir=null;
File uploadDir=null;
public void init(ServletConfig config) throws ServletException {
// Put your code here
super.init(config);
String realPath = config.getServletContext().getRealPath("/pic");
uploadDir = new File(realPath);
String tempPath = System.getProperty("java.io.tmpdir");
if (tempPath == null) {
tempPath = realPath + "/temp";
}
tempDir = new File(tempPath);
}


public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}


public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session=request.getSession(true);
DiskFileItemFactory factory=new DiskFileItemFactory();
ServletFileUpload upload=new ServletFileUpload(factory);
upload.setFileSizeMax(2 * 1024 * 1024);
factory.setRepository(tempDir);
List fileNames = new ArrayList();
List list;
try{
list=upload.parseRequest(request);
} catch (FileUploadException e) {
throw new RuntimeException("上传出错", e);
}
Iterator it=list.iterator();
while(it.hasNext()){
FileItem fi=(FileItem)it.next();
String name="";
if(!fi.isFormField()&&fi.getName().length()>0){
name=fi.getName().substring(fi.getName().lastIndexOf(""));
InputStream is = fi.getInputStream();
BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(new File(uploadDir+name)));
IOUtils.copy(is, os);
IOUtils.closeQuietly(is);
IOUtils.closeQuietly(os);
fileNames.add(name);
}
}
session.setAttribute("uploadFileNames", fileNames);
request.getRequestDispatcher("upload-success.jsp").forward(request,
response);

}

}
结果报错
 java.io.FileNotFoundException:E:\webWorkspace\file\WebRoot\pic(拒绝访问。)
我pic文件夹是建好的 请问为什么

------解决方案--------------------
uploadDir 我看程序里是file类型,name是String类型
它们2个怎么能加在一起?你用的编辑器没有报错吗?
BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(new File(realpath+"\\"+name)));
这样试试吧