javarequest文件上传
文件上传就是将客户端资源,通过网路传递到服务器端。
因为文件数据比较大,必须通过文件上传才可以完成将数据保存到数据库端的操作。
文件上传的本质就是IO流操作。
演示:文件上传应该如何操作?
浏览器端:
1.method=post 只有post才可以携带大数据
2.必须使用<input type='file' name='f'>要有name属性
3.encType="multipart/form-data"
服务器端:
request对象是用于获取请求信息。
它有一个方法 getInputStream(); 可以获取一个字节输入流,通过这个流,可以读取到
所有的请求正文信息.
文件上传原理:
浏览器端注意上述三件事,在服务器端通过流将数据读取到,在对数据进行解析.
将上传文件内容得到,保存在服务器端,就完成了文件上传。
注意:在实际开发中,不需要我们进行数据解析,完成文件上传。因为我们会使用文件上传的工具,它们已经封装好的,提供API,只要调用它们的API就可以完成文件上传操作.我们使用的commons-fileupload,它是apache提供的一套开源免费的文件上传工具。
代码演示文件上传的原理:
在WebRoot下新建upload1.jsp
[html]view plain
<%@pagelanguage="java"import="java.util.*"pageEncoding="UTF-8"%>
<!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01Transitional//EN">
<html>
<head>
<title>MyJSP'index.jsp'startingpage</title>
</head>
<body>
<!--encType默认是application/x-www-form-urlencoded-->
<formaction="${pageContext.request.contextPath}/upload1"
method="POST"enctype="multipart/form-data">
<inputtype="text"name="content"><br>
<inputtype="file"name="f"><br><inputtype="submit"
value="上传">
</form>
</body>
</html>
packagecn.itcast.web.servlet;
importjava.io.IOException;
importjava.io.InputStream;
importjavax.servlet.ServletException;
importjavax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
{
publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)
throwsServletException,IOException{
//System.out.println("upload1servlet......");
//通过request获取一个字节输入流,将所有的请求正文信息读取到,打印到控制台
InputStreamis=request.getInputStream();
byte[]b=newbyte[1024];
intlen=-1;
while((len=is.read(b))!=-1){
System.out.println(newString(b,0,len));
}
is.close();
}
publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)
throwsServletException,IOException{
doGet(request,response);
}
}
在web页面中添加上传输入项。
在Servlet中读取上传文件的数据,并保存在服务器硬盘中。
1、必须设置input输入项的name属性,否则浏览器将不会发送上传文件的数据。
2、必须把form的encType属性设为multipart/form-data 设置该值后,浏览器在上传文件时,并把文件数据附带在http请求消息体内,并使用MIME协议对上传的文件进行描述,以方便接收方对上传数据进行解析和处理。
3、表单的提交方式要设置为post。
Request对象提供了一个getInputStream方法,通过这个方法可以读取到客户端提交过来的数据。但由于用户可能会同时上传多个文件,在servlet端编程直接读取上传数据,并分别解析出相应的文件数据是一项非常麻烦的工作,示例。
为方便用户处理文件上传数据,Apache 开源组织提供了一个用来处理表单文件上传的一个开源组件( Commons-fileupload ),该组件性能优异,并且其API使用极其简单,可以让开发人员轻松实现web文件上传功能,因此在web开发中实现文件上传功能,通常使用Commons-fileupload组件实现。
使用Commons-fileupload组件实现文件上传,需要导入该组件相应支撑jar包:Commons-fileupload和commons-io。commo-io不属于文件上传组件的开发jar文件,但Commons-fileupload组件从1.1版本开始,它工作时需要commons-io包的支持。
新建Upload1Servlet 路径:/upload1
[java]view plain
在浏览器端访问信息如下:
文件上传概述
实现web开发中的文件上传功能,需要完成如下二步操作:
如何在web页面中添加上传输入项?
<input type="file">标签用于在web页面中添加文件上传输入项,设置文件上传输入项时注意:
如何在Servlet中读取文件上传数据,并保存到本地硬盘中?
⑵ Java利用HttpURLConnection发送post请求上传文件
在页面里实现上传文件不是什么难事 写个form 加上enctype = multipart/form data 在写个接收的就可以了 没租裤什么难的 如果要用 HttpURLConnection来实现文件上传 还真有点搞头 : )
先写个servlet把接收到的 HTTP 信息保存在一个文件中 看一下 form 表单到底封装了什么样的信息
Java代码
public void doPost(HttpServletRequest request HttpServletResponse response)
throws ServletException IOException {
//获取输入流 是HTTP协议中的实体内容
ServletInputStream in=request getInputStream();
//缓冲区
byte buffer[]=new byte[ ];
FileOutputStream out=new FileOutputStream( d:\test log );
int len=sis read(buffer );
//把流里的信息循环读入到file log文件中
while( len!= ){
out write(buffer len);
len=in readLine(buffer );
}
out close();
in close();
}
来一个form表单
<form name= upform action= upload do method= POST
enctype= multipart/form data >
参数<input type= text name= username /><br/>
文件 <input type= file name= file /><br/>
文件 <input type= file name= file /><br/>
<input type= submit value= Submit />
<br />
</form>
假如我参数写的内容是hello word 然后二个文件是二个简单的txt文件梁誉 上传后test log里如下
Java代码
da e c
Content Disposition: form data; name= username
hello word
da e c
Content Disposition: form data; name= file ; filename= D:haha txt
Content Type: text/plain
haha
hahaha
da e c
Content Disposition: form data; name= file ; filename= D:huhu txt
Content Type: text/plain
messi
huhu
da e c
研究下规律发现有如下几点特征
第一行是 d b bc 作为分隔符 然后是 回车换行符 这个 d b bc 分隔符浏览器是随机生成的
第二行是Content Disposition: form data; name= file ; filename= D:huhu txt ;name=对应input的name值 filename对应要上传的文件名(包括路径在内)
第三行如果是文件就有Content Type: text/plain 这里上传的是txt文件所以是text/plain 如果上穿的是jpg图片的话就是image/jpg了 可以自己试试看看
然后就是回弊渣简车换行符
在下就是文件或参数的内容或值了 如 hello word
最后一行是 da e c 注意最后多了二个 ;
有了这些就可以使用HttpURLConnection来实现上传文件功能了
Java代码 public void upload(){
List<String> list = new ArrayList<String>(); //要上传的文件名 如 d:haha doc 你要实现自己的业务 我这里就是一个空list
try {
String BOUNDARY = d a d c ; // 定义数据分隔线
URL url = new URL( );
HttpURLConnection conn = (HttpURLConnection) url openConnection();
// 发送POST请求必须设置如下两行
conn setDoOutput(true);
conn setDoInput(true);
conn setUseCaches(false);
conn setRequestMethod( POST );
conn setRequestProperty( connection Keep Alive );
conn setRequestProperty( user agent Mozilla/ (patible; MSIE ; Windows NT ; SV ) );
conn setRequestProperty( Charsert UTF );
conn setRequestProperty( Content Type multipart/form data; boundary= + BOUNDARY);
OutputStream out = new DataOutputStream(conn getOutputStream());
byte[] end_data = ( + BOUNDARY + ) getBytes();// 定义最后数据分隔线
int leng = list size();
for(int i= ;i<leng;i++){
String fname = list get(i);
File file = new File(fname);
StringBuilder *** = new StringBuilder();
*** append( );
*** append(BOUNDARY);
*** append( );
*** append( Content Disposition: form data;name= file +i+ ;filename= + file getName() + );
*** append( Content Type:application/octet stream );
byte[] data = *** toString() getBytes();
out write(data);
DataInputStream in = new DataInputStream(new FileInputStream(file));
int bytes = ;
byte[] bufferOut = new byte[ ];
while ((bytes = in read(bufferOut)) != ) {
out write(bufferOut bytes);
}
out write( getBytes()); //多个文件时 二个文件之间加入这个
in close();
}
out write(end_data);
out flush();
out close();
// 定义BufferedReader输入流来读取URL的响应
BufferedReader reader = new BufferedReader(new InputStreamReader(conn getInputStream()));
String line = null;
while ((line = reader readLine()) != null) {
System out println(line);
}
} catch (Exception e) {
System out println( 发送POST请求出现异常! + e);
e printStackTrace();
}
lishixin/Article/program/Java/hx/201311/27114
⑶ java 上传文件 问题
不用 下载相应jar包 引入就可以了 import 你懂得
⑷ java实现文件上传,代码尽量简洁~~~~~·
你说的2种方法都是很简单的,参考网上的资料都不难做出,用io流做更是基础中的基础,我说下smartupload好了,有的人是直接写在jsp上面,感觉比较乱,我一般都是写在action里面,打好jar包和配置后
SmartUpload mySmartUpload = new SmartUpload();
//如果是struts2.0或者webwork 则是mySmartUpload.initialize(ServletActionContext.getServletConfig(),ServletActionContext.getRequest(),ServletActionContext.getResponse());
mySmartUpload.initialize(servlet.getServletConfig(), request,response);
mySmartUpload.setTotalMaxFileSize(500000);
//如果上传任意文件不设置mySmartUpload.setAllowedFilesList(文件后缀名)就可以了
mySmartUpload.upload();
for (int i = 0; i < mySmartUpload.getFiles().getCount(); i++) {
com.jspsmart.upload.File file = mySmartUpload.getFiles().getFile(i);
if (file.isMissing()) continue;
file.saveAs(保存的地址 + file.getFileName(),
su.SAVE_PHYSICAL);
⑸ java使用ServletFileUpload上传文件,ServletFileUpload.parseRequest(request)报错。
操作不允许,/trs/apache-tomcat-7.0.37/yy/kjcg/uploadtmp/upload__bf6b7e9_14520c5a8b9__8000_00000000.tmp不能创建。查查tomcat所属用户的/trs/apache-tomcat-7.0.37/yy/kjcg/uploadtmp目录写权限