servlet实现文件上传的三种方法总结
1. 通过getinputstream()取得上传文件。
/**
* to change this template, choose tools | templates
* and open the template in the editor.
*/
package net.individuals.web.servlet;
import java.io.datainputstream;
import java.io.fileoutputstream;
import java.io.ioexception;
import javax.servlet.servletexception;
import javax.servlet.annotation.webservlet;
import javax.servlet.http.httpservlet;
import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpservletresponse;
/**
*
* @author barudisshu
*/
@webservlet(name = "uploadservlet", urlpatterns = {"/uploadservlet"})
public class uploadservlet extends httpservlet {
/**
* processes requests for both http
* <code>get</code> and
* <code>post</code> methods.
*
* @param request servlet request
* @param response servlet response
* @throws servletexception if a servlet-specific error occurs
* @throws ioexception if an i/o error occurs
*/
protected void processrequest(httpservletrequest request, httpservletresponse response)
throws servletexception, ioexception {
response.setcontenttype("text/html;charset=utf-8");
//读取请求body
byte[] body = readbody(request);
//取得所有body内容的字符串表示
string textbody = new string(body, "iso-8859-1");
//取得上传的文件名称
string filename = getfilename(textbody);
//取得文件开始与结束位置
position p = getfileposition(request, textbody);
//输出至文件
writeto(filename, body, p);
}
//构造类
class position {
int begin;
int end;
public position(int begin, int end) {
this.begin = begin;
this.end = end;
}
}
private byte[] readbody(httpservletrequest request) throws ioexception {
//获取请求文本字节长度
int formdatalength = request.getcontentlength();
//取得servletinputstream输入流对象
datainputstream datastream = new datainputstream(request.getinputstream());
byte body[] = new byte[formdatalength];
int totalbytes = 0;
while (totalbytes < formdatalength) {
int bytes = datastream.read(body, totalbytes, formdatalength);
totalbytes += bytes;
}
return body;
}
private position getfileposition(httpservletrequest request, string textbody) throws ioexception {
//取得文件区段边界信息
string contenttype = request.getcontenttype();
string boundarytext = contenttype.substring(contenttype.lastindexof("=") + 1, contenttype.length());
//取得实际上传文件的气势与结束位置
int pos = textbody.indexof("filename="");
pos = textbody.indexof("n", pos) + 1;
pos = textbody.indexof("n", pos) + 1;
pos = textbody.indexof("n", pos) + 1;
int boundaryloc = textbody.indexof(boundarytext, pos) - 4;
int begin = ((textbody.substring(0, pos)).getbytes("iso-8859-1")).length;
int end = ((textbody.substring(0, boundaryloc)).getbytes("iso-8859-1")).length;
return new position(begin, end);
}
private string getfilename(string requestbody) {
string filename = requestbody.substring(requestbody.indexof("filename="") + 10);
filename = filename.substring(0, filename.indexof("n"));
filename = filename.substring(filename.indexof("n") + 1, filename.indexof("""));
return filename;
}
private void writeto(string filename, byte[] body, position p) throws ioexception {
fileoutputstream fileoutputstream = new fileoutputstream("e:/workspace/" + filename);
fileoutputstream.write(body, p.begin, (p.end - p.begin));
fileoutputstream.flush();
fileoutputstream.close();
}
// <editor-fold defaultstate="collapsed" desc="httpservlet methods. click on the + sign on the left to edit the code.">
/**
* handles the http
* <code>get</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws servletexception if a servlet-specific error occurs
* @throws ioexception if an i/o error occurs
*/
@override
protected void doget(httpservletrequest request, httpservletresponse response)
throws servletexception, ioexception {
processrequest(request, response);
}
/**
* handles the http
* <code>post</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws servletexception if a servlet-specific error occurs
* @throws ioexception if an i/o error occurs
*/
@override
protected void dopost(httpservletrequest request, httpservletresponse response)
throws servletexception, ioexception {
processrequest(request, response);
}
/**
* returns a short description of the servlet.
*
* @return a string containing servlet description
*/
@override
public string getservletinfo() {
return "short description";
}// </editor-fold>
}
2. 通过getpart()、getparts()取得上传文件。
body格式:
post http://www.example.com http/1.1
content-type:multipart/form-data; boundary=----webkitformboundaryrgkcby7qhfd3trwa
------webkitformboundaryrgkcby7qhfd3trwa
content-disposition: form-data; name="text"
title
------webkitformboundaryrgkcby7qhfd3trwa
content-disposition: form-data; name="file"; filename="chrome.png"
content-type: image/png
png ... content of chrome.png ...
------webkitformboundaryrgkcby7qhfd3trwa--
[html] view plain copy
/**
* to change this template, choose tools | templates
* and open the template in the editor.
*/
package net.individuals.web.servlet;
import java.io.filenotfoundexception;
import java.io.fileoutputstream;
import java.io.ioexception;
import java.io.inputstream;
import java.io.outputstream;
import javax.servlet.servletexception;
import javax.servlet.annotation.multipartconfig;
import javax.servlet.annotation.webservlet;
import javax.servlet.http.httpservlet;
import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpservletresponse;
import javax.servlet.http.part;
/**
*
* @author barudisshu
*/
@multipartconfig
@webservlet(name = "uploadservlet", urlpatterns = {"/uploadservlet"})
public class uploadservlet extends httpservlet {
/**
* processes requests for both http
* <code>get</code> and
* <code>post</code> methods.
*
* @param request servlet request
* @param response servlet response
* @throws servletexception if a servlet-specific error occurs
* @throws ioexception if an i/o error occurs
*/
protected void processrequest(httpservletrequest request, httpservletresponse response)
throws servletexception, ioexception {
part part = request.getpart("photo");
string filename = getfilename(part);
writeto(filename, part);
}
//取得上传文件名
private string getfilename(part part) {
string header = part.getheader("content-disposition");
string filename = header.substring(header.indexof("filename="") + 10, header.lastindexof("""));
return filename;
}
//存储文件
private void writeto(string filename, part part) throws ioexception, filenotfoundexception {
inputstream in = part.getinputstream();
outputstream out = new fileoutputstream("e:/workspace/" + filename);
byte[] buffer = new byte[1024];
int length = -1;
while ((length = in.read(buffer)) != -1) {
out.write(buffer, 0, length);
}
in.close();
out.close();
}
// <editor-fold defaultstate="collapsed" desc="httpservlet methods. click on the + sign on the left to edit the code.">
/**
* handles the http
* <code>get</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws servletexception if a servlet-specific error occurs
* @throws ioexception if an i/o error occurs
*/
@override
protected void doget(httpservletrequest request, httpservletresponse response)
throws servletexception, ioexception {
processrequest(request, response);
}
/**
* handles the http
* <code>post</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws servletexception if a servlet-specific error occurs
* @throws ioexception if an i/o error occurs
*/
@override
protected void dopost(httpservletrequest request, httpservletresponse response)
throws servletexception, ioexception {
processrequest(request, response);
}
/**
* returns a short description of the servlet.
*
* @return a string containing servlet description
*/
@override
public string getservletinfo() {
return "short description";
}
}
3、另一种较为简单的方法:采用part的wirte(string filename)上传,浏览器将产生临时tmp文件
/**
* to change this template, choose tools | templates
* and open the template in the editor.
*/
package net.individuals.web.servlet;
import java.io.ioexception;
import java.io.printwriter;
import javax.servlet.servletexception;
import javax.servlet.annotation.multipartconfig;
import javax.servlet.annotation.webservlet;
import javax.servlet.http.httpservlet;
import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpservletresponse;
import javax.servlet.http.part;
/**
*采用part的wirte(string filename)上传,浏览器将产生临时tmp文件。
* @author barudisshu
*/
@multipartconfig(location = "e:/workspace")
@webservlet(name = "uploadservlet", urlpatterns = {"/uploadservlet"})
public class uploadservlet extends httpservlet {
/**
* processes requests for both http
* <code>get</code> and
* <code>post</code> methods.
*
* @param request servlet request
* @param response servlet response
* @throws servletexception if a servlet-specific error occurs
* @throws ioexception if an i/o error occurs
*/
protected void processrequest(httpservletrequest request, httpservletresponse response)
throws servletexception, ioexception {
//处理中文文件名
request.setcharacterencoding("utf-8");
part part = request.getpart("photo");
string filename = getfilename(part);
//将文件写入location指定的目录
part.write(filename);
}
private string getfilename(part part) {
string header = part.getheader("content-disposition");
string filename = header.substring(header.indexof("filename="") + 10, header.lastindexof("""));
return filename;
}
// <editor-fold defaultstate="collapsed" desc="httpservlet methods. click on the + sign on the left to edit the code.">
/**
* handles the http
* <code>get</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws servletexception if a servlet-specific error occurs
* @throws ioexception if an i/o error occurs
*/
@override
protected void doget(httpservletrequest request, httpservletresponse response)
throws servletexception, ioexception {
processrequest(request, response);
}
/**
* handles the http
* <code>post</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws servletexception if a servlet-specific error occurs
* @throws ioexception if an i/o error occurs
*/
@override
protected void dopost(httpservletrequest request, httpservletresponse response)
throws servletexception, ioexception {
processrequest(request, response);
}
/**
* returns a short description of the servlet.
*
* @return a string containing servlet description
*/
@override
public string getservletinfo() {
return "short description";
}// </editor-fold>
}
以上就是servlet实现文件上传的实例,如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
【说明】:本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!