|
10Java金币
我做了一个关于文件上传的测试,用到common-io与common-upload.
工程运行后,txt文件上传成功,但是上传的txt文件的内容是空的,求助。
Servlet如下:
package com.hui.servlet;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletContext;
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.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class UploadServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/HTML");
PrintWriter out = response.getWriter();
String task=request.getParameter("task");
if(task.equals("upload")){
request.getRequestDispatcher("/upload/fileupload.jsp").forward(request, response);
}else if(task.equals("save")){
/* int i=0;
InputStream inputStream=request.getInputStream();
while(!((i=inputStream.read())==-1)){
System.out.print((char)i);
}*/
DiskFileItemFactory factory=new DiskFileItemFactory();
ServletFileUpload upload=new ServletFileUpload(factory);
try {
List<FileItem>filelist=upload.parseRequest(request);
for(FileItem item:filelist){
if(item.isFormField()==true){
String filedname=item.getFieldName();
String filedvalue=item.getString("UTF-8");
System.out.println(filedname+"======"+filedvalue);
}else{
String filename=item.getName();
InputStream inputStream=request.getInputStream();
ServletContext servletContext=this.getServletContext();
String filepath=servletContext.getRealPath("/uploads");
OutputStream outputStream=new FileOutputStream(filepath+"/"+filename);
System.out.println(filepath);
int i=0;
byte[] b=new byte[1024];
while((i=inputStream.read(b))!=-1){
outputStream.write(b,0,i);
}
inputStream.close();
outputStream.close();
}
}
} catch (FileUploadException e) {
e.printStackTrace();
}
}
out.flush();
out.close();
}
}
|
|