关于文件上传和下载的问题
求大神教我怎么用java的servlet无任何组件的情况下上传或下载文件
[解决办法]
servlet+jsp实现图片或其他文件的上传
[解决办法]
文件的下载
[解决办法]
貌似这个不能用啊,DiskFileItemFactory和ServletFileUpload这两个类报错
引jar包呀
[解决办法]
把二楼给你的代码搞清楚后自己在写一下就好了,学习怎么可以一点不动脑筋呀?
[解决办法]
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.servlet.http.HttpServletResponse;
public class FileUtil2 {
/**
* 上传文件
*
* @param file
* @param filePath
*
* @throws Exception
*/
public static void runUploadFile(File file, String filePath) throws Exception
{
InputStream streamIn = null;
OutputStream streamOut = null;
if (file != null)
{
try
{
streamOut = new FileOutputStream(filePath);
streamIn = new FileInputStream(file);;
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = streamIn.read(buffer, 0, 8192)) != -1) { streamOut.write(buffer, 0, bytesRead);}
}catch(IOException e)
{
e.fillInStackTrace();
}finally
{
try
{
if(streamIn != null)
streamIn.close();
if(streamOut != null)
streamOut.close();
}
catch (IOException e)
{
}
}
}
}
/**
* 下载文件
*
* @param filePath
* @param response
*
* @throws Exception
*/
public static void runDownFile(String filePath, HttpServletResponse response) throws Exception
{
try
{
File file = new File(filePath);
String fileName = new String(filePath.substring(filePath.lastIndexOf("\\")+1, filePath.length()).getBytes("gbk"),"ISO-8859-1"); //windows
response.setContentType("application");
//response.setHeader("Content-Disposition", "attachment; filename=" + fileName.replace(fileName.subSequence(fileName.lastIndexOf("."), fileName.length()), ".zip"));
response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
FileInputStream fis=new FileInputStream(file);
BufferedInputStream buff=new BufferedInputStream(fis);
byte [] b=new byte[1024];//相当于我们的缓存
long k=0;//该值用于计算当前实际下载了多少字节
//从response对象中得到输出流,准备下载
OutputStream myout=response.getOutputStream();
//开始循环下载
while(k<file.length()){
int j=buff.read(b,0,1024);
k+=j;
//将b中的数据写到客户端的内存
myout.write(b,0,j);
}
//将写入到客户端的内存的数据,刷新到磁盘
buff.close();
fis.close();
myout.close();
myout.flush();
}
catch (FileNotFoundException se)
{
se.printStackTrace();
}
catch(IOException e)
{
e.printStackTrace();
}
}
}