日期:2014-05-20  浏览次数:20798 次

急求JSP上传图片问题
找了好多,就是成功不了!
希望曾成功过的把代码发出来,并且把步骤写出来,谢谢了!!!

------解决方案--------------------

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletInputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UploadHandle {

private ServletInputStream in = null;
private ServletOutputStream out = null;
private HttpServletRequest request = null;
private HttpServletResponse response = null;

private String boundary = " ";
private String strEndFlag = " ";
private boolean bStreamNotEnd = true;
private static String savePath = "./upload/ ";
private int fileSize = 0;

private long maxFileSize = 20000000;


public UploadHandle(HttpServletRequest request, HttpServletResponse
response, String savePath2) {
this.request = request;
this.response = response;
try {
in = request.getInputStream();
out = response.getOutputStream();

if (savePath2 != null && !savePath2.equals( " ")) {
savePath = savePath2;
} else {
String strAppPath = System.getProperty( "user.dir ");
savePath = strAppPath + "/upload/ ";
}
File file = new File(savePath);
file.mkdirs();
file = null;
} catch (Exception e) {
}

}

public void setMaxFileSize(long maxFileSize) {
this.maxFileSize = maxFileSize;
}

public void go() throws Exception {
String strContentType = request.getContentType();
boundary = "-- " +
strContentType.substring(strContentType.indexOf( "boundary= ") + 9);
strEndFlag = boundary + "-- ";

String strParameterName = " ";
String strParameterValue = " ";
String strFileName = " ";
String[] strArrFiles = new String[]{ " ", " ", " ", " "};

String strLine = " ";

Matcher matcher = null;
String strPattern = " ";
strPattern = "Content-Disposition: form-data;
name=\ "([\\p{Print}&&[^\ "]]+)\ "(; filename=\ "(.+)\ ")? ";
bStreamNotEnd = true;
while (bStreamNotEnd && !(strLine = readLine()).equals(strEndFlag)) {
matcher = Pattern.compile(strPattern,
Pattern.CASE_INSENSITIVE).matcher(strLine);
if (matcher.find()) {
strParameterName = matcher.group(1);
strFileName = matcher.group(3);
// System.out.println( "strParameterName: " + strParameterName);
// System.out.println( "strFileName: " + strFileName);

while (!this.readLine().equals( " ")){}

if (strFileName != null) {
strFileName = strFileName.replace( "\\ ", "/ ");
if(strFileName.lastIndexOf( "/ ") > -1) {
strFileName = strFileName.substring(strFileName.lastIndexOf( "/ ") + 1);
}
String str2 = " ";
if(strFileName.indexOf( ". ") > -1) {
str2 = strFileName.substring(strFileName.lastIndexOf( ". "));
}

strFileName = (new DateUtil()).getDateTime().replace( ": ", "_ ").replace( "
", "_ ") + "_ " + ((int) (Math.random() * 10000000)) + " " + str2; //(new
DateUtil()).getDateTime().replace( ": ", " ' ").replace( " ", "_ ") + "_ " +