上傳,用COMMONS FILEUPLOAD,用法略:
具體可以看下面的例子:主要是SERVLET
package oa.home.servlet;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import java.sql.*;
import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import oa.home.system.SysFunction;
import oa.home.system.*;
import oa.home.log.Log;
import oa.home.basicbean.model.*;
import oa.home.basicbean.sql.*;
import oa.home.dbconnect.DBConnect;
import oa.home.exception.*;
public class HtfbWServlet
extends HttpServlet {
private static final String CONTENT_TYPE = "text/html; charset=GBK";
//Initialize global variables
public void init() throws ServletException {
}
//Process the HTTP Get request
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.setContentType(CONTENT_TYPE);
PrintWriter out = response.getWriter();
String act = SysFunction.converString(request.getParameter("act"));
String modelName = null; //范本名稱
int conTypeDictID = 0; //范本類型
int specialTypeID = 0; //適應(yīng)專業(yè)
String beginTime = null; //開始時(shí)間
String endTime = null; //結(jié)束時(shí)間
String fileExt = null; //文件后綴名
Connection conn = null;
FileItem fileItem = null; //文件列
FileItem fileItem1 = null; //文件列
boolean err = false; //是否出錯(cuò)
int nownode = 0; //最后執(zhí)行的代碼
int contractModelID = 0;
DiskFileUpload diskFileUpload = new DiskFileUpload();
// 允許文件最大長度
diskFileUpload.setSizeMax(100 * 1024 * 1024);
// 設(shè)置內(nèi)存緩沖大小
diskFileUpload.setSizeThreshold(1024*1024);
// 設(shè)置臨時(shí)目錄
diskFileUpload.setRepositoryPath("c:/temp");
String strDirPath = new File(request.getSession().getServletContext().getRealPath(request.getRequestURI())).getParent();
strDirPath = strDirPath.substring(0,strDirPath.length()-2);//目錄的絕對路徑 類似D:\Documents and Settings\Administrator\jbproject/untitled10\oa
//System.out.println("目錄的絕對路徑:" + strDirPath );
List fileItems = null;
try {
fileItems = diskFileUpload.parseRequest(request);
}
catch (FileUploadException ex) {
err = true;
Log.println("fileuploadEX in HtfbWServlet :" + ex);
}
Iterator iter = fileItems.iterator();
while (iter.hasNext()) {
fileItem = (FileItem) iter.next();
if (fileItem.isFormField()) {
// 當(dāng)前是一個(gè)表單項(xiàng)
if ("modelName".equals(fileItem.getFieldName()))
modelName = fileItem.getString();
if ("conTypeDictID".equals(fileItem.getFieldName()))
conTypeDictID = SysFunction.converInt(fileItem.getString());
if ("specialTypeID".equals(fileItem.getFieldName()))
specialTypeID = SysFunction.converInt(fileItem.getString());
if ("beginTime".equals(fileItem.getFieldName()))
beginTime = SysFunction.converString(fileItem.getString());
if ("endTime".equals(fileItem.getFieldName()))
endTime = SysFunction.converString(fileItem.getString());
}
else {
// 當(dāng)前是一個(gè)上傳的文件
fileItem1 = fileItem; //如果是文件,則將fileItem賦給另一個(gè)fileItem1.
String fileName = fileItem.getName();
fileExt = fileName.substring(fileName.length() - 4);//文件后綴名,帶圓點(diǎn)"."
}
}
//開始添加
if (act.equals("add")) {
ContractModelBean contractModel = new ContractModelBean();
contractModel.setModelName(modelName);
contractModel.setConTypeDictID(conTypeDictID);
contractModel.setSpecialtyClassDictID(specialTypeID);
contractModel.setBeginTime(beginTime);
contractModel.setEndTime(endTime);
contractModel.setExt(fileExt);
contractModel.setUploadPath(strDirPath+BasicInfo.UPLOADPATH);
contractModel.setIsEnable(0);
try {
conn = DBConnect.getConnection();
contractModel = ContractModelHome.create(conn, contractModel);
contractModelID = contractModel.getID();
}
catch (SystemException ex1) {
err = true;
Log.println("SysEX in HtfbWServlet :" + ex1);
}
catch (SQLException ex1) {
err = true;
Log.println("SQLEX in HtfbWServlet :" + ex1);
}
if (contractModelID != 0) { //當(dāng)create成功時(shí),即contractModel不為空時(shí),再上傳文件
try {
//開始上傳
String file = strDirPath+BasicInfo.UPLOADPATH + modelName +fileExt;
fileItem1.write(new File(file));
}
catch (Exception ex1) {
err = true;
Log.println("fileuploadEX in HtfbWServlet :" + ex1);
}
finally {
if (!err) {
nownode = 49;
if (conn != null) {
try {
conn.close();
}
catch (SQLException ex2) {
Log.error(getClass().getName() + ":updateDeptDict 不能關(guān)閉數(shù)據(jù)庫連接" +
ex2);
}
}
}
}
}
}
response.sendRedirect("yewu/czzhihou.jsp?nownode="+nownode+"&basicRollID="+
contractModelID);
}
//Process the HTTP Post request
public void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
doGet(request, response);
}
//Clean up resources
public void destroy() {
}
}
下載:
JSP下載
JSP文件下載及出現(xiàn)getOutputStream() has already been called for this response的解決方法
http://iamin./iamin/1072546.html
一、采用RequestDispatcher的方式進(jìn)行
1、web.xml文件中增加
<mime-mapping>
<extension>doc</extension>
<mime-type>application/vnd.ms-word</mime-type>
</mime-mapping>
2、程序如下:
<%@page language="java" import="java.net.*" pageEncoding="gb2312"%>
<%
response.setContentType("application/x-download");//設(shè)置為下載
String filenamedownload = "/系統(tǒng)解決方案.doc";//即將下載的文件的相對路徑
String filenamedisplay = "系統(tǒng)解決方案.doc";//下載文件時(shí)顯示的文件保存名稱
filenamedisplay = URLEncoder.encode(filenamedisplay,"UTF-8");
response.addHeader("Content-Disposition","attachment;filename=" + filenamedisplay);
try
{
RequestDispatcher dispatcher = application.getRequestDispatcher(filenamedownload);
if(dispatcher != null)
{
dispatcher.forward(request,response);
}
response.flushBuffer();
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
}
%>
二、采用文件流輸出的方式下載
1、web.xml文件中增加
<mime-mapping>
<extension>doc</extension>
<mime-type>application/vnd.ms-word</mime-type>
</mime-mapping>
2、程序如下:
<%@page language="java" contentType="application/x-msdownload" import="java.io.*,java.net.*" pageEncoding="gb2312"%><%
//關(guān)于文件下載時(shí)采用文件流輸出的方式處理:
//加上response.reset(),并且所有的%>后面不要換行,包括最后一個(gè);
//因?yàn)锳pplication Server在處理編譯jsp時(shí)對于%>和<%之間的內(nèi)容一般是原樣輸出,而且默認(rèn)是PrintWriter,
//而你卻要進(jìn)行流輸出:ServletOutputStream,這樣做相當(dāng)于試圖在Servlet中使用兩種輸出機(jī)制,
//就會發(fā)生:getOutputStream() has already been called for this response的錯(cuò)誤
//詳細(xì)請見《More Java Pitfill》一書的第二部分 Web層Item 33:試圖在Servlet中使用兩種輸出機(jī)制 270
//而且如果有換行,對于文本文件沒有什么問題,但是對于其它格式,比如AutoCAD、Word、Excel等文件
//下載下來的文件中就會多出一些換行符0x0d和0x0a,這樣可能導(dǎo)致某些格式的文件無法打開,有些也可以正常打開。
response.reset();//可以加也可以不加
response.setContentType("application/x-download");//1、unknown ==> application/x-download
//../../退WEB-INF/classes兩級到應(yīng)用的根目錄下去
String filenamedownload = this.getClass().getClassLoader().getResource("/").getPath() + "../../系統(tǒng)解決方案.doc";
String filenamedisplay = "系統(tǒng)解決方案.doc";//系統(tǒng)解決方案.txt
filenamedisplay = URLEncoder.encode(filenamedisplay,"UTF-8");
response.addHeader("Content-Disposition","attachment;filename=" + filenamedisplay);
OutputStream output = null;
FileInputStream fis = null;
try
{
output = response.getOutputStream();
fis = new FileInputStream(filenamedownload);
byte[] b = new byte[1024];
int i = 0;
while((i = fis.read(b)) > 0)
{
output.write(b, 0, i);
}
output.flush();
}
catch(Exception e)
{
System.out.println("Error!");
e.printStackTrace();
}
finally
{
if(fis != null)
{
fis.close();
fis = null;
}
if(output != null)
{
output.close();
output = null;
}
}
%>
SERVLET下載
package oa.home.basicbean.sql.viewsql;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
import oa.home.basicbean.model.*;
import oa.home.basicbean.sql.viewsql.*;
import oa.home.basicbean.sql.*;
import oa.home.dbconnect.DBConnect;
import oa.home.log.Log;
import oa.home.exception.*;
import oa.home.system.*;
public class FileDownSvt
extends HttpServlet {
//設(shè)置此項(xiàng)即告訴SERVLET是下載文件,而不是網(wǎng)頁或TXT.(可以彈出對話框)
private static final String CONTENT_TYPE = "APPLICATION/OCTET-STREAM";
public void init() throws ServletException {
}
//Process the HTTP Get request
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.setContentType(CONTENT_TYPE);
// PrintWriter out = response.getWriter();
//注意,這里給注釋掉了,如果不注釋會出現(xiàn)
java.lang.IllegalStateException: getWriter() has already been called for this response
這樣的錯(cuò)誤.,這是因?yàn)閷懳募鲿r(shí),已經(jīng)有個(gè)GETWRITER打開了.,但在下面輸出時(shí),可以在IF{}內(nèi)用.
//Clears any data that exists in the buffer as well as the status code and headers. If the response has been committed, this method throws an IllegalStateException.
response.reset();
//用IntputStream時(shí),就用下面這個(gè).
ServletOutputStream outputStream = response.getOutputStream();
InputStream inputStream = null;
int ID = SysFunction.converInt(request.getParameter("ID"));
ContractModelBean bean = null;
String fileName = ""; //文件名,包括后綴名
String filePath = ""; //文件路徑,包括文件名+后綴名
if (ID != -1) {
try {
Connection conn = DBConnect.getConnection();
bean = ContractModelHome.findById(conn, ID);
}
catch (SystemException ex) {
Log.println("SYSerr in FileDownSvt :" + ex);
}
catch (SQLException ex) {
Log.println("SQLerr in FileDownSvt :" + ex);
}
if (bean != null) {
fileName = bean.getModelName() + bean.getExt();
filePath = bean.getUploadPath() + fileName;
//轉(zhuǎn)換下載中文名的問題. 注意這一行,不能放到上面filePath = bean.getUploadPath() + fileName;
這一句的上面去了.不然下載的文件名會是亂碼
fileName = new String(fileName.getBytes("GBK"), "ISO8859_1");
//設(shè)置下載的文件名與原文件名一樣.
response.setHeader("Content-Disposition",
"attachment; filename=\"" + fileName + "\"");
File file = new File(filePath);
inputStream = new FileInputStream(file);
int chunk = inputStream.available(); //設(shè)每次讀CHUNK個(gè)字節(jié),inputStream.available()為當(dāng)時(shí)可讀的文件字節(jié).因?yàn)樵趧傞_始時(shí)讀,所以這里實(shí)際為文件大小
if (chunk == 0 || chunk == 1024*1024*60)
chunk = 1024*1024;
//byte數(shù)組接受文件的數(shù)據(jù)
byte[] buffer = new byte[chunk];
int length = -1;
try {
if (inputStream == null) {
Log.println("輸入流為空!!");
}
else {
while ( (length = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, length); //讀入流,保存在BYTe數(shù)組中
}
}
inputStream.close();
outputStream.flush();
outputStream.close(); //這三句一定要寫.特別是FLUSH(),不然文件下載不完整.
}
catch (IOException ex1) {
Log.println("IOerr in FileDownSvt :" + ex1);
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head><title>Down</title></head>");
out.println("<body bgcolor=\"#ffffff\">");
out.println("<p> Err!!!! is not this file!!</p>");
out.println("</body></html>");
}
}
}
}
//Process the HTTP Post request
public void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
doGet(request, response);
}
//Clean up resources
public void destroy() {
}
}