DBMNG数据库管理与应用

独立思考能力,对于从事科学研究或其他任何工作,都是十分必要的。
当前位置:首页 > 服务器配置 > Resin

Resin4.0+Servlet3.0实现文件上传操作

Servlet3.0支持文件的上传,而不必另外调用common-fileupload.jar等第三方组件。

Tomcat7.0开始支持Servlet3.0,Resin4.0也支持Servlet3.0。

但是最近使用Resin4+Servlet3.0实现文件上传操作时,发现一个问题-就是当调用直接写入文件的part.write("服务器文件写入绝对路径")这一句时,resin4.0总是会提示string越界-1的错误,但是同样的程序使用Tomcat7.0运行没有问题可以直接上传文件,而且在resin4.0下运行时从header中获取的中文文件名也是乱码。经过一番研究,终获解决(并参考了网上流行的一段乱码解决方案的代码,同时解决中文乱码的兼容性问题)。现录于此,仅供参考。

java端代码:

package com.test;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
//IOStream
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
//Servlet3.0 specific annotations
import javax.servlet.annotation.WebServlet;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.Part;

@WebServlet(description = "FileUploadServlet Description", urlPatterns = { "/FileUploadServlet" })
@MultipartConfig
public class FileUploadServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	public FileUploadServlet() {
		super();
		System.out.println("FileUploadServlet Initialized & Instantiated.");
	}

	public void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//System.out.println("Accept-Encoding : " + request.getHeader("Accept-Encoding")); 

		//System.out.println("request编码方式:"+request.getCharacterEncoding());
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=utf-8");
		//System.out.println("request编码方式:"+request.getCharacterEncoding());
		//System.out.println("Accept-Encoding : " + request.getHeader("Accept-Encoding")); 

		PrintWriter out = response.getWriter();
		out.println("<html><head><body>");
		for (Part part : request.getParts()) {
			//String fileName = "";
			String partHeader = part.getHeader("content-disposition");
			//byte[]t=partHeader.getBytes();
			//System.out.println("是否乱码:="+toUTF8(partHeader));
			
			//if(partHeader.indexOf("?")>-1)//判断有乱码时自动重新尝试编码
			partHeader=toUTF8(partHeader);//new String(partHeader.getBytes("ISO-8859-1"),"UTF-8");//resin4
			long partSize = part.getSize();
			out.println("<BR>Part Name = " + part.getName());
			out.println("<BR>Part Header = " + partHeader);
			out.println("<BR>Part Size = " + partSize);
			System.out.println(">>>>>>>part.getHeader(\"content-disposition\") = "+ partHeader);
		}
		out.println("<center><h1>++++File Upload Completed Successfully</h1></center></body></html>");

		// **** Custom Option ****//
		System.out.println("自定义上传文件名");
		fileUploadWithDesiredFilePathAndName(request);
		System.out.println("使用自定义方式上传文件.");
	}

	/*
	 * Following method allows us to place the uploaded file in a desired
	 * Location on the server along with the desired fileName
	 */
	public void fileUploadWithDesiredFilePathAndName(HttpServletRequest request)
			throws IOException, ServletException {
		/******** Following part of code is not needed ********/
		InputStream inputStream = null;
		FileOutputStream outputStream = null;
		try {
			for (Part part : request.getParts()) {
				System.out.println(part.getName());
				inputStream = request.getPart(part.getName()).getInputStream();
				int i = inputStream.available();
				byte[] b = new byte[i];
				inputStream.read(b);
				System.out.println("Length : " + b.length);

				// Finding the fileName //
				String fileName = "";
				String partHeader = part.getHeader("content-disposition");
				//if(partHeader.indexOf("?")>-1)//判断有乱码时自动重新尝试编码
				partHeader=toUTF8(partHeader);//new String(partHeader.getBytes("ISO-8859-1"),"UTF-8");//resin4
				System.out.println("Part Header = " + partHeader);
				System.out.println("====part.getHeader(\"content-disposition\") = "+ partHeader);

				for (String temp : partHeader.split(
						";")) {
					if (temp.trim().startsWith("filename")) {
						fileName = temp.substring(temp.indexOf('=') + 1).trim().replace("\"", "");
					}
				}
				String tempExtName=fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase().trim();
				fileName=""+System.currentTimeMillis()+"."+tempExtName;
				//System.out.println(new String(fileName.getBytes(),"UTF-8"));
				//System.out.println(new String(fileName.getBytes(),"GBK"));
				//fileName=new String(fileName.getBytes("ISO-8859-1"),"UTF-8");
				System.out.println(fileName);
				//System.out.println(new String(fileName.getBytes("ISO-8859-1"),"GBK"));
				// Writing contents to desired FilePath & FileName //
				String uploadDir = "c:/temp/";
				System.out.println("File will be Uploaded at: " + uploadDir
						+ "/" + fileName);
				outputStream = new FileOutputStream(uploadDir + "/" + fileName);
				outputStream.write(b);
				inputStream.close();
			}
		} catch (Exception e) {
			System.out.println("Unable to Upload File: " + e);
			e.printStackTrace();
		} finally {
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			if (outputStream != null) {
				try {
					outputStream.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	

private  static  String  toUTF8(String  str)  { 
           if  (str  ==  null)  return  null; 
           String  retStr  =  str; 
           byte  b[]; 
           try  { 
                   b  =  str.getBytes("ISO8859_1");
                   for  (int  i  =  0;  i  <  b.length;  i++)  { 
                           byte  b1  =  b[i]; 
                           if  (b1  ==  63) 
                                   break;    //1 
                           else  if  (b1  >  0) 
                                   continue;//2 
                           else  if  (b1  <  0)  {        //不可能为0,0为字符串结束符
//小于0乱码
                                   retStr  =  new  String(b,  "UTF-8"); 
                                   break; 
                           } 
                   } 
           }  catch  (UnsupportedEncodingException  e)  { 
                   //  e.printStackTrace();  
           } 
           return  retStr; 
   } 
	
}
html页面代码:
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<html>
    <head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
        <title>FileUpload</title>
    </head>
    <body>
      <center>
        <h1>FileUpload Demo Using Servlet3.0</h1>
        <form id="formId" action="FileUploadServlet" enctype="multipart/form-data" method="post">
          <input type="file" id="FileUploadId" name="Upload"  />
          <!-- input type="file" id="FileUploadId2" name="Upload2"  / -->
          <input type="submit" id="uploadButtonId" value="开始上传" />
        </form>
      </center>
    </body>
</html>
本站文章内容,部分来自于互联网,若侵犯了您的权益,请致邮件chuanghui423#sohu.com(请将#换为@)联系,我们会尽快核实后删除。
Copyright © 2006-2023 DBMNG.COM All Rights Reserved. Powered by DEVSOARTECH            豫ICP备11002312号-2

豫公网安备 41010502002439号