原文:http://blog.youkuaiyun.com/feichexia/article/details/7105741
http://zhangjunhd.blog.51cto.com/113473/19631
http://blog.youkuaiyun.com/kanaka10/article/details/6526630
response.setContentType() 的作用是使客户端浏览器,区分不同种类的数据,并根据不同的MIME调用浏览器内不同的程序嵌入模块来处理相应的数据。例如web浏览器就是通过MIME 类型来判断文件是GIF图片。通过MIME类型来处理json字符串。
Tomcat的安装目录/conf/web.xml 中就定义了大量MIME类型 ,你可也去看一下。
用表单上传文件,想在服务端验证上传文件的类型,只允许上传GIF,JPG,ZIP, 我们有两种方法:
第一:检查文件的扩展名;
第二:检查文件的MIME类型 。
检查文件的扩展名的方法,很简单快捷,但是 a.jsp 改名为 a.jpg能可以绕过检查上传了。
检查文件的MIME类型的方法,在IE7与Firefox下有一点区别(见下表),有不同浏览器上传表现不一致。Firefox下ZIP与EXE文件的MIME类型同为application/octet-stream。
表中例出的是在服务器端(tomcat5.5)接收不同浏览器上传的文件时,取得的MIME类型
| 用IE7上传 | 用Firefox3.0上传 |
GIF | image/gif | image/gif |
JPG | image/pjpeg | image/jpeg |
ZIP | application/x-compressed | application/octet-stream |
JSP | text/html | text/html |
EXE | application/octet-stream | application/octet-stream |
常见MIME类型例表:
序号 | 内容类型 | 文件扩展名 | 描述 |
1 | application/msword | doc | Microsoft Word |
2 | application/octet-stream bin | dms lha lzh exe class | 可执行程序 |
3 | application/pdf | | Adobe Acrobat |
4 | application/postscript | ai eps ps | PostScript |
5 | appication/powerpoint | ppt | Microsoft Powerpoint |
6 | appication/rtf | rtf | rtf 格式 |
7 | appication/x-compress | z | unix 压缩文件 |
8 | application/x-gzip | gz | gzip |
9 | application/x-gtar | gtar | tar 文档 (gnu 格式 ) |
10 | application/x-shockwave-flash | swf | MacroMedia Flash |
11 | application/x-tar | tar | tar(4.3BSD) |
12 | application/zip | zip | winzip |
13 | audio/basic | au snd | sun/next 声音文件 |
14 | audio/mpeg | mpeg mp2 | Mpeg 声音文件 |
15 | audio/x-aiff | mid midi rmf | Midi 格式 |
16 | audio/x-pn-realaudio | ram ra | Real Audio 声音 |
17 | audio/x-pn-realaudio-plugin | rpm | Real Audio 插件 |
18 | audio/x-wav | wav | Microsoft Windows 声音 |
19 | image/cgm | cgm | 计算机图形元文件 |
20 | image/gif | gif | COMPUSERVE GIF 图像 |
21 | image/jpeg | jpeg jpg jpe | JPEG 图像 |
22 | image/png | png | PNG 图像 |
|
|
|
|
text/html HTML
text/plain TXT
text/xml XML
text/json json字符串
此外不同浏览器下对同一个文件上传后获取到的类型可能不同。
1.客户端上传文件
-----------------------------7d71042a40328
Content-Disposition: form-data; name="fileforload"; filename="C:\Documents and Settings\ZJ\桌面\book.txt"
Content-Type: text/plain
//此处为文件内容
-----------------------------7d71042a40328
Content-Disposition: form-data; name="submit"
commit
-----------------------------7d71042a40328--
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>This page for FileUpload</title>
</head>
<body>
<p>Choose the file for uploading:
<form action="accept.jsp" method=post enctype="multipart/form-data">
<input type=file name=fileforload size=30>
<br>
<input type=submit value=commit name=submit>
</form>
</body>
</html>
accept.jsp
<html>
<head>
<%@ page language="java" import="java.io.*" %>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>This page for response</title>
</head>
<body>
<%
try {
if (request.getContentLength() > 297) {
InputStream in = request.getInputStream();
File f = new File("d:/temp", "test.txt");
FileOutputStream o = new FileOutputStream(f);
byte b[] = new byte[1024];
int n;
while ((n = in.read(b)) != -1) {
o.write(b, 0, n);
}
o.close();
in.close();
out.print("File upload success!");
} else {
out.print("No file!");
}
} catch (IOException e) {
out.print("upload error.");
e.printStackTrace();
}
%>
</body>
</html>
服务器端得到的上传文件I like.txt,取名为test.txt
-----------------------------7d75b1540328
Content-Disposition: form-data; name="fileforload"; filename="C:\Documents and Settings\ZJ\桌面\I like.txt"
Content-Type: text/plain
我喜欢驾驭着代码在风驰电掣中创造完美;
我喜欢操纵着代码在随心所欲中体验生活;
我喜欢用心情代码编制我小小的与众不同;
每一段新的代码在我手中延生对我来说就象观看刹那花开的感动;
我不需要焦点.因为我就是焦点!
-----------------------------7d75b1540328
Content-Disposition: form-data; name="submit"
commit
-----------------------------7d75b1540328--
<html>
<head>
<%@ page language="java" import="java.io.*" %>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>The real file</title>
</head>
<body>
<%try{
//use sessionid to create a temp file.
String tempFileName=(String)session.getId();
//create the temp file.
File temp=new File("d:/temp",tempFileName);
FileOutputStream o=new FileOutputStream(temp);
if(request.getContentLength()>297){
//write the upload content to the temp file.
InputStream in=request.getInputStream();
byte b[]=new byte[1024];
int n;
while((n=in.read(b))!=-1){
o.write(b,0,n);
}
o.close();
in.close();
//read the temp file.
RandomAccessFile random=new RandomAccessFile(temp,"r");
//read Line2 to find the name of the upload file.
int second=1;
String secondLine=null;
while(second<=2){
secondLine=random.readLine();
second++;
}
//get the last location of the dir char.'\\'.
int position=secondLine.lastIndexOf('\\');
//get the name of the upload file.
String fileName=secondLine.substring(position+1,secondLine.length()-1);
//relocate to the head of file.
random.seek(0);
//get the location of the char.'Enter' in Line4.
long forthEndPosition=0;
int forth=1;
while((n=random.readByte())!=-1&&(forth<=4)){
if(n=='\n'){
forthEndPosition=random.getFilePointer();
forth++;
}
}
File realFile=new File("d:/temp",fileName);
RandomAccessFile random2=new RandomAccessFile(realFile,"rw");
//locate the end position of the content.Count backwards 6 lines.
random.seek(random.length());
long endPosition=random.getFilePointer();
long mark=endPosition;
int j=1;
while((mark>=0)&&(j<=6)){
mark--;
random.seek(mark);
n=random.readByte();
if(n=='\n'){
endPosition=random.getFilePointer();
j++;
}
}
//locate to the begin of content.Count for 4 lines's end position.
random.seek(forthEndPosition);
long startPoint=random.getFilePointer();
//read the real content and write it to the realFile.
while(startPoint<endPosition-1){
n=random.readByte();
random2.write(n);
startPoint=random.getFilePointer();
}
random2.close();
random.close();
//delete the temp file.
temp.delete();
out.print("File upload success!");
}
else{
out.print("No file!");
}
}
catch(IOException e){
out.print("upload error.");
e.printStackTrace();
}
%>
</body>
</html>
文件下载的关键代码在于:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>download page</title>
</head>
<body>
<a href=loadFile>Download:test.zip</a>
</body>
</html>
LoadFile.java
package com.zj.sample;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoadFile extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
OutputStream o = response.getOutputStream();
byte b[] = new byte[1024];
// the file to download.
File fileLoad = new File("d:/temp", "test.rar");
// the dialogbox of download file.
response.setHeader("Content-disposition", "attachment;filename="
+ "test.rar");
// set the MIME type.
response.setContentType("application/x-tar");
// get the file length.
long fileLength = fileLoad.length();
String length = String.valueOf(fileLength);
response.setHeader("Content_Length", length);
// download the file.
FileInputStream in = new FileInputStream(fileLoad);
int n = 0;
while ((n = in.read(b)) != -1) {
o.write(b, 0, n);
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
doGet(request, response);
}
}
web.xml(注册servlet)
<servlet>
<servlet-name>LoadFileServlet</servlet-name>
<servlet-class>com.zj.sample.LoadFile</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoadFileServlet</servlet-name>
<url-pattern>/loadFile</url-pattern>
</servlet-mapping>