上傳:
需要導入兩個包:commons-fileupload-1.2.1.jar,commons-io-1.4.jar
import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
/**
* 上傳附件
* @author new
*
*/
public class UploadAnnexServlet extends HttpServlet {
private static String path = "";
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
/*
* post處理
* (non-Javadoc)
* @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
path = this.getServletContext().getRealPath("/upload");
try {
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload up = new ServletFileUpload(factory);
List<FileItem> ls = up.parseRequest(request);
for (FileItem fileItem : ls) {
if (fileItem.isFormField()) {
String FieldName = fileItem.getFieldName();
//getName()返回的是文件名字 普通域沒有文件 返回NULL
// String Name = fileItem.getName();
String Content = fileItem.getString("gbk");
request.setAttribute(FieldName, Content);
} else {
String nm = fileItem.getName().substring(
fileItem.getName().lastIndexOf("\\") + 1);
File mkr = new File(path, nm);
if (mkr.createNewFile()) {
fileItem.write(mkr);//非常方便的方法
}
request.setAttribute("result", "上傳文件成功!");
}
}
} catch (Exception e) {
e.printStackTrace();
request.setAttribute("result", "上傳失敗,請查找原因,重新再試!");
}
request.getRequestDispatcher("/pages/admin/annex-manager.jsp").forward(
request, response);
}
}
下載(i/o流)無需導包:
import java.io.IOException;
import java.net.URLEncoder;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 下載文件
* @author
*
*/
public class DownloadFilesServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 8594448765428224944L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
/*
* 處理請求
* (non-Javadoc)
* @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String name = request.getParameter("fileName");
System.out.print("dddddddddd:" + name);
// web絕對路徑
String path = request.getSession().getServletContext().getRealPath("/");
String savePath = path + "upload";
// 設置為下載application/x-download
response.setContentType("application/x-download");
// 即將下載的文件在伺服器上的絕對路徑
String filenamedownload = savePath + "/" + name;
// 下載文件時顯示的文件保存名稱
String filenamedisplay = name;
// 中文編碼轉換
filenamedisplay = URLEncoder.encode(filenamedisplay, "UTF-8");
response.addHeader("Content-Disposition", "attachment;filename="
+ filenamedisplay);
try {
java.io.OutputStream os = response.getOutputStream();
java.io.FileInputStream fis = new java.io.FileInputStream(
filenamedownload);
byte[] b = new byte[1024];
int i = 0;
while ((i = fis.read(b)) > 0) {
os.write(b, 0, i);
}
fis.close();
os.flush();
os.close();
} catch (Exception e) {
}
}
}
② 怎麼用servlet上傳文件到該WEB項目的WebRoot的某文件夾下啊是相對路徑不是絕對路徑,請問怎麼做啊
這個問題我以前也有過,但後來我明白了,雖然說JSP能編譯為Servlet但是,這只是web容器的功勞。你要是邊幾個項目就會明白。好的WEB程序里。JSP和HTML文件的編寫是一樣的。除了一些必要的處理代碼塊。但是很少有。一般處理請求的都放在了servlet里,現在Struts很好的封裝了Servlet這一層,成為了servelt的專業框架。用來處理用戶的請求。但有必要的時候,我們還必須自己去寫Servlet,比如過濾器,再比如監聽器等。
所以說,雖然JSP能編譯為Servlet但並不代表他就能替代Servlet。一般的web項目盡量將顯示代碼放進jsp中
而處理代碼放進Servlet中。以增加可讀性,可拓展性。可維護性。可能我說的有點深奧,但是你以後去做項目時就會明白了。
JSP是絕不能替代Servlet的。希望對你有幫助。
③ java如何將導出的excel下載到客戶端
packagecom.mr;
importjava.io.IOException;
importjava.io.PrintWriter;
importjavax.servlet.ServletException;
importjavax.servlet.ServletOutputStream;
importjavax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
/**
*利用Servlet導出Excel
*@N
*
*/
{
publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)
throwsServletException,IOException{
doPost(request,response);
}
publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)
throwsServletException,IOException{
request.setCharacterEncoding("UTF-8");//設置request的編碼方式,防止中文亂碼
StringfileName="導出數據";//設置導出的文件名稱
StringBuffersb=newStringBuffer(request.getParameter("tableInfo"));//將表格信息放入內存
StringcontentType="application/vnd.ms-excel";//定義導出文件的格式的字元串
StringrecommendedName=newString(fileName.getBytes(),"iso_8859_1");//設置文件名稱的編碼格式
response.setContentType(contentType);//設置導出文件格式
response.setHeader("Content-Disposition","attachment;filename="+recommendedName+""");//
response.resetBuffer();
//利用輸出輸入流導出文件
ServletOutputStreamsos=response.getOutputStream();
sos.write(sb.toString().getBytes());
sos.flush();
sos.close();
}
}
<%@pagelanguage="java"contentType="text/html;charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPEhtmlPUBLIC"-//W3C//DTDHTML4.01Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=UTF-8">
<title>導出Excel</title>
<scripttype="text/javascript">
functiontest(){
document.getElementById("tableInfo").value=document.getElementById("table").innerHTML;
}
</script>
<style>
body{font-family:宋體;font-size:11pt}
</style>
</head>
<body>
<formaction="<%=request.getContextPath()%>/servlet/ExportExcelServlet"method="post">
<spanid="table">
<tablebgcolor="#EEECF2"bordercolor="#A3B2CC"border="1"cellspacing="0">
<tr><th>學號</th><th>姓名</th><th>科目</th><th>分數</th></tr>
<tr><td>10001</td><td>趙二</td><td>高數</td><td>82</td></tr>
<tr><td>10002</td><td>張三</td><td>高數</td><td>94</td></tr>
<tr><td>10001</td><td>趙二</td><td>線數</td><td>77</td></tr>
<tr><td>10002</td><td>張三</td><td>線數</td><td>61</td></tr>
</table>
</span><br/>
<inputtype="submit"name="Excel"value="導出表格"onclick="test()"/>
<inputtype="hidden"id="tableInfo"name="tableInfo"value=""/>
</form>
</body>
</html>
以上代碼來自網路:http://jtlyuan.iteye.com/blog/1322097
④ java:servlet接收圖片,並把它保存到資料庫中
這種代碼網上不是一大片嗎
publicbooleanstoreImage(Filefile){
try{
//打開文件
FileInputStreamfin=newFileInputStream(file);
//建一個緩沖保存數據
ByteBuffernbf=ByteBuffer.allocate((int)file.length());
byte[]array=newbyte[1024];
intoffset=0,length=0;
//讀存數據
while((length=fin.read(array))>0){
if(length!=1024)nbf.put(array,0,length);
elsenbf.put(array);
offset+=length;
}
//關閉文件
fin.close();
//新建一個數組保存要寫的內容
byte[]content=nbf.array();
Stringsql="insertintoimages(bin_data)values(?)";
PreparedStatementpstmt=conn.prepareStatement(sql);
pstmt.setBytes(1,content);
pstmt.execute();
pstmt.close();
}catch(Exceptione){
e.printStackTrace();
returnfalse;
}
returntrue;
}
⑤ java jsp中如何實現下載.csv文件、並自動保存到指定的文件夾下
你這種想法來不太現實
首先你客戶端自要跟伺服器交互是要客戶端主動發送請求
然後建立連接去操作
就算你不手動選保存路徑,那你還是要寫代碼去實現這個過程的
實現方式就兩種了
bs跟cs架構均可
思路是一樣的
BS:
servlet讀取本地文件,然後以流的形式輸出就行,注意要設置輸出的MINE類型也就是contentType
你客戶端寫個程序通過http訪問這個servlet,然後通過程序去保存到你移動硬碟
如果是cs架構的話,你的服務端監聽socket
如果有客戶端連接那就等待接收命令或者是直接往客戶端傳文件的二進制流
客戶端:已啟動就連接服務端,發送文件請求,處理回傳的文件位元組流