一、文件的下載html
在下載時首先要設置MIME類型;app
(1)servlet框架
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//聲明MIME類型。
response.setContentType("application/x-msdownload");
//設置要上傳的文件
File file=new File("e:"+File.separator+"hello.txt");
//獲取上傳的文件的名字
String fileName=file.getName();
//輸入文件
InputStream intStream=new FileInputStream(file);
//輸出文件
OutputStream out=response.getOutputStream();
//在下載時使下載的文件與上傳的文件的名字一致
response.setHeader("Content-Disposition", "attachment;filename="+fileName+"");
if (!file.exists()) {
System.out.println("文件不存在");
}else{
byte[] b=new byte[1024];
int len=0;
while ((len=intStream.read(b))!=-1) {
out.write(b, 0, len);
}
}if (out!=null) {//關閉流
out.close();
}if (intStream!=null) {
intStream.close();
}
}spa
(2)index.htmlhtm
<a href="download">下載文件</a>utf-8
2文件的上傳get
1)利用Tomcat3.0新特性進行多個文件上傳servlet
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Collection<Part> part=request.getParts();
//foreach寫法
/* int len=part.size();
if (len==1) {
Part part1=request.getPart("file");
String filename=getName(part1);
String path="e:"+File.separator+filename;
part1.write(path);
}else {
for (Part part2 : part) {
String filename=getName(part2);
String path="e:"+File.separator+filename;
part2.write(path);
}
}*/
//迭代器寫法
Iterator<Part> iterator=part.iterator();
while (iterator.hasNext()) {
Part part2 = (Part) iterator.next();
String filename=getName(part2);
String path="e:"+File.separator+filename;
part2.write(path);
}
}
//獲取上傳文件的名字
public String getName(Part part){
String head=part.getHeader("Content-Disposition");
int lastindex=head.lastIndexOf("\"");
int firstindex=head.lastIndexOf("\"", lastindex-1);
String filename=head.substring(firstindex+1, lastindex);
return filename;
}文件上傳
2)使用第三方框架進行多個文件進行上傳string
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
request.setCharacterEncoding("utf-8");
DiskFileItemFactory factory=new DiskFileItemFactory();//得到磁盤條目工廠
String path="e:"+File.separator;//上傳的路徑
factory.setRepository(new File(path));
factory.setSizeThreshold(1024*1024);
//高水平的API文件上傳處理
ServletFileUpload fileUpload=new ServletFileUpload(factory);
List<FileItem> list;
try {
list = (List<FileItem>)fileUpload.parseRequest(request); for (FileItem fileItem : list) { String filename=fileItem.getName(); try { //利用第三方框架進行上傳 fileItem.write(new File(path, filename)); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } catch (FileUploadException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } }