struts2文件上傳下載及亂碼問題解決

java和jsp文件的編碼都是UTF-8 的

文件下載

private String inputPath;<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

public void setInputPath(String value) throws UnsupportedEncodingException {

inputPath = new String(value.getBytes("ISO-8859-1"),"UTF-8");

}

public InputStream getInputStream() throws Exception {

if(log.isDebugEnabled()){

log.debug("inputPath="+inputPath);

}

return new java.io.FileInputStream(inputPath);

// return ServletActionContext.getServletContext().getResourceAsStream(inputPath);

//使用上面的語句將無法獲取到inputStream,如果資源恰好在web應用下面,則是可以的。

}

/**

* 下載日誌文件

* @return

* @throws Excepiton

*/

public String download () throws Exception{

String fileName = inputPath.substring(inputPath.lastIndexOf(java.io.File.separator)+1, inputPath.length());

if(log.isDebugEnabled()){

log.debug("fileName="+fileName);

}

ServletActionContext.getResponse().setHeader("Content-Disposition", "attachment; filename="+new String(fileName.getBytes("gb2312"),"iso-8859-1"));

return SUCCESS;

}

注意:第一個轉換,"ISO-8859-1"————"UTF-8" UTF-8是根據你自己的編碼來處理
第二個轉換,"gb2312"————"iso-8859-1" 你就不要改變了,不管你是什麼編碼,都這麼處理就是了,只要你的客戶用的是中文的操作系統,呵呵

配置文件的內容

<action name="download" class="com.work.qxgl.loglogin.LogLoginAction"

method="downloadLogs">

<result name="success" type="stream">

<param name="inputName">inputStream</param>

<param name="bufferSize">4096</param>

</result>

</action>

下載設置

<a href='<s:url action="download" namespace="/qxglloglogin"><s:param name="inputPath" value="filePath" /></s:url>'><s:property value="fileName" /></a>

文件上傳

public File getUpload() {

return upload;

}

public void setUpload(File upload) {

this.upload = upload;

}

// since we are using <s:file name="upload" .../> the file name will be

// obtained through getter/setter of <file-tag-name>FileName

/**

* 如果表單域爲fj,那麼就叫getFjFileName;

* @return

*/

public String getUploadFileName() {

return fileName;

}

public void setUploadFileName(String fileName) {

this.fileName = fileName;

}

// since we are using <s:file name="upload" ... /> the content type will be

// obtained through getter/setter of <file-tag-name>ContentType

/**

* 如果表單域爲fj,那麼就叫getFjContentType

* @return

*/

public String getUploadContentType() {

return contentType;

}

public void setUploadContentType(String contentType) {

this.contentType = contentType;

}

在配置文件中限制上傳文件的格式

< action name ="fileUpload" class ="tutorial.FileUploadAction" >
< interceptor-ref name ="fileUpload" >
< param name ="allowedTypes" >
image/bmp,image/png,image/gif,image/jpeg
</ param >

</ interceptor-ref >

< interceptor-ref name ="defaultStack" />

< result name ="input" > /FileUpload.jsp </ result >

< result name ="success" > /ShowUpload.jsp </ result >
</ action >

發佈了3 篇原創文章 · 獲贊 0 · 訪問量 2664
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章