有两段代码 但是我不知道是哪一段才是限制非法字符
代码1
<input type="button" name="btn_UpLoad" id="btn_UpLoad" runat="server" value="上传图片" onClick="window.open('../Public/UpLoadFile.aspx?FormName=Form1&EditName=txt_LogoUrl&ImageName=img_Logo&ExtName=jpg&UpPath=Company_Logo','','status=no,scrollbars=no,top=20,left=110,width=420,height=165')">代码2
<%@ Page language="c#" %>
<script runat="server">
private string NoFileMessage = "您没有选择文件。";
private string UploadSuccessMessage = "上传成功";
private string UploadFailureMessage = "上传失败。";
private string NoFolderSpecifiedMessage = "您要上传到的文件夹不存在。";
private string InvalidFileTypeMessage = "您无法上传这种类型的文件。";
private string[] AcceptedFileTypes = new string[] {"jpg","jpeg","gif","JPG","JPEG","GIF"};
private string DefaultImageFolder = "UploadFiles"; // 默认的起始文件夹
private void Page_Load(object sender, System.EventArgs e)
{
string isframe = "" + Request["frame"];
if (isframe != "")
{
MainPage.Visible = true;
iframePanel.Visible = false;
string FileErrorMessage = "只允许上传以下类型的文件:";
string ValidationString = ".*(";
for (int i=0;i<AcceptedFileTypes.Length; i++)
{
ValidationString += "[\\." + AcceptedFileTypes[i] + "]";
if (i < (AcceptedFileTypes.Length-1)) ValidationString += "|";
FileErrorMessage += AcceptedFileTypes[i];
if (i < (AcceptedFileTypes.Length-1)) FileErrorMessage += ", ";
}
FileValidator.ValidationExpression = ValidationString+")$";
FileValidator.ErrorMessage=FileErrorMessage;
} else {
}
}
public void UploadImage_OnClick(object sender, EventArgs e)
{
if ( UploadFile.PostedFile.FileName.ToString().Trim() != "" )
{
string AppPath = HttpContext.Current.Request.PhysicalApplicationPath;
string AppUrl;
if (Request.ApplicationPath == "/")
AppUrl = Request.ApplicationPath;
else
AppUrl = Request.ApplicationPath + "/";
string ImageFileLocation = AppUrl;
ImageFileLocation = ImageFileLocation.Substring(ImageFileLocation.LastIndexOf("\\")+1);
ImageFileLocation += DefaultImageFolder;
ImageFileLocation += "/";
string UploadFileName = "";
string UploadFileDestination = "";
UploadFileName = UploadFile.PostedFile.FileName;
UploadFileName = UploadFileName.Substring(UploadFileName.LastIndexOf("\\")+1);
string ImageFileExtention = UploadFileName.Substring(UploadFileName.LastIndexOf("."));
UploadFileDestination = HttpContext.Current.Request.PhysicalApplicationPath;
UploadFileDestination += DefaultImageFolder;
UploadFileDestination += "\\";
string NewFileName = DateTime.Now.Year.ToString()+DateTime.Now.Month.ToString()+DateTime.Now.Day.ToString()+DateTime.Now.Hour.ToString()+DateTime.Now.Minute.ToString()+DateTime.Now.Second.ToString();
UploadFile.PostedFile.SaveAs(UploadFileDestination + NewFileName + ImageFileExtention);
System.Drawing.Image image = System.Drawing.Image.FromFile(UploadFileDestination + NewFileName + ImageFileExtention);
Response.Write("<script>var arr=new Array();arr['filename']='"+ImageFileLocation+NewFileName + ImageFileExtention+"';arr['width']='"+image.Width+"';arr['height']='"+image.Height+"';window.parent.returnValue = arr;window.parent.close();<" + "/" + "script>");
}
}
private bool IsValidFileType(string FileName) {
string ext = FileName.Substring(FileName.LastIndexOf(".")+1,FileName.Length-FileName.LastIndexOf(".")-1);
for (int i=0; i<AcceptedFileTypes.Length; i++) {
if (ext == AcceptedFileTypes[i]) {
return true;
}
}
return false;
}
</script>
<asp:panel id="MainPage" runat="server" visible="false">
<!doctype html public "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
<META HTTP-EQUIV="Expires" CONTENT="0">
<title>插入图片</title>
<style>
body {
margin: 0px 0px 0px 0px;
padding: 0px 0px 0px 0px;
background: #ffffff;
width: 100%;
overflow:hidden;
border: 0;
}
body,tr,td {
color: #000000;
font-family: Verdana, Arial, Helvetica, sans-serif;
font-size: 10pt;
}
div.imagespacer {
width: 120;
height: 126;
text-align: center;
float: left;
font: 10pt verdana;
margin: 5px;
overflow: hidden;
}
div.imageholder {
margin: 0px;
padding: 0px;
border: 1 solid #CCCCCC;
width: 100;
height: 100;
}
div.titleholder {
font-family: ms sans serif, arial;
font-size: 8pt;
width: 100;
text-overflow: ellipsis;
overflow: hidden;
white-space: nowrap;
}
</style>
<script language="javascript">
lastDiv = null;
function divClick(theDiv,filename) {
if (lastDiv) {
lastDiv.style.border = "1 solid #CCCCCC";
}
lastDiv = theDiv;
theDiv.style.border = "2 solid #316AC5";
document.getElementById("FileToDelete").value = filename;
}
function showimg(){
document.all.imgview.innerHTML="<img src='"+document.all.UploadFile.value+"'>";
}
function returnImage(imagename,width,height) {
var arr = new Array();
arr["filename"] = imagename;
arr["width"] = width;
arr["height"] = height;
window.parent.returnValue = arr;
window.parent.close();
}
</script>
</HEAD>
<body>
<table width=100% height=100% cellpadding=0 cellspacing=0 border=0>
<FORM encType="multipart/form-data" runat="server" ID="Form1">
<tr><td>
<div id="galleryarea" style="width=100%; height:100%; overflow: auto;">
<asp:label id="gallerymessage" runat="server"></asp:label>
<asp:panel id="GalleryPanel" runat="server"></asp:panel>
<span id="imgview"></span>
</div>
</td></tr>
<asp:Panel id="UploadPanel" runat="server">
<tr><td height=16 style="padding-left:10px;border-top: 1 solid #999999; background-color:#99ccff;">
<table>
<tr>
<td valign=top><input id="UploadFile" type="file" name="UploadFile" onchange="showimg()" runat="server" style="width:300;"/></td>
<td valign=top><asp:button id="UploadImage" Text="上传" runat="server" onclick="UploadImage_OnClick" /></td>
</tr>
<tr>
<td colspan=3>
<asp:RegularExpressionValidator runat="server"
ControlToValidate="UploadFile"
id="FileValidator" display="dynamic"/>
<asp:literal id="ResultsMessage" runat="server" />
</td>
</tr></table>
<input type="hidden" id="RootImagesFolder" Value="images" runat="server" NAME="RootImagesFolder"/>
</td></tr>
</asp:panel>
</form>
</table>
</body>
</HTML>
</asp:panel>
<asp:panel id="iframePanel" runat="server" >
<html>
<head><title>插入图片</title></head>
<style>
body {
margin: 0px 0px 0px 0px;
padding: 0px 0px 0px 0px;
background: #ffffff;
overflow:hidden;
}
</style>
<body>
<iframe style="width:100%;height:100%;border:0;" border=0 frameborder=0 src="ftb.imagegallery.aspx?frame=1&<%=Request.QueryString%>"></iframe>
</body>
</html>
</asp:panel>
代码1
<input type="button" name="btn_UpLoad" id="btn_UpLoad" runat="server" value="上传图片" onClick="window.open('../Public/UpLoadFile.aspx?FormName=Form1&EditName=txt_LogoUrl&ImageName=img_Logo&ExtName=jpg&UpPath=Company_Logo','','status=no,scrollbars=no,top=20,left=110,width=420,height=165')">代码2
<%@ Page language="c#" %>
<script runat="server">
private string NoFileMessage = "您没有选择文件。";
private string UploadSuccessMessage = "上传成功";
private string UploadFailureMessage = "上传失败。";
private string NoFolderSpecifiedMessage = "您要上传到的文件夹不存在。";
private string InvalidFileTypeMessage = "您无法上传这种类型的文件。";
private string[] AcceptedFileTypes = new string[] {"jpg","jpeg","gif","JPG","JPEG","GIF"};
private string DefaultImageFolder = "UploadFiles"; // 默认的起始文件夹
private void Page_Load(object sender, System.EventArgs e)
{
string isframe = "" + Request["frame"];
if (isframe != "")
{
MainPage.Visible = true;
iframePanel.Visible = false;
string FileErrorMessage = "只允许上传以下类型的文件:";
string ValidationString = ".*(";
for (int i=0;i<AcceptedFileTypes.Length; i++)
{
ValidationString += "[\\." + AcceptedFileTypes[i] + "]";
if (i < (AcceptedFileTypes.Length-1)) ValidationString += "|";
FileErrorMessage += AcceptedFileTypes[i];
if (i < (AcceptedFileTypes.Length-1)) FileErrorMessage += ", ";
}
FileValidator.ValidationExpression = ValidationString+")$";
FileValidator.ErrorMessage=FileErrorMessage;
} else {
}
}
public void UploadImage_OnClick(object sender, EventArgs e)
{
if ( UploadFile.PostedFile.FileName.ToString().Trim() != "" )
{
string AppPath = HttpContext.Current.Request.PhysicalApplicationPath;
string AppUrl;
if (Request.ApplicationPath == "/")
AppUrl = Request.ApplicationPath;
else
AppUrl = Request.ApplicationPath + "/";
string ImageFileLocation = AppUrl;
ImageFileLocation = ImageFileLocation.Substring(ImageFileLocation.LastIndexOf("\\")+1);
ImageFileLocation += DefaultImageFolder;
ImageFileLocation += "/";
string UploadFileName = "";
string UploadFileDestination = "";
UploadFileName = UploadFile.PostedFile.FileName;
UploadFileName = UploadFileName.Substring(UploadFileName.LastIndexOf("\\")+1);
string ImageFileExtention = UploadFileName.Substring(UploadFileName.LastIndexOf("."));
UploadFileDestination = HttpContext.Current.Request.PhysicalApplicationPath;
UploadFileDestination += DefaultImageFolder;
UploadFileDestination += "\\";
string NewFileName = DateTime.Now.Year.ToString()+DateTime.Now.Month.ToString()+DateTime.Now.Day.ToString()+DateTime.Now.Hour.ToString()+DateTime.Now.Minute.ToString()+DateTime.Now.Second.ToString();
UploadFile.PostedFile.SaveAs(UploadFileDestination + NewFileName + ImageFileExtention);
System.Drawing.Image image = System.Drawing.Image.FromFile(UploadFileDestination + NewFileName + ImageFileExtention);
Response.Write("<script>var arr=new Array();arr['filename']='"+ImageFileLocation+NewFileName + ImageFileExtention+"';arr['width']='"+image.Width+"';arr['height']='"+image.Height+"';window.parent.returnValue = arr;window.parent.close();<" + "/" + "script>");
}
}
private bool IsValidFileType(string FileName) {
string ext = FileName.Substring(FileName.LastIndexOf(".")+1,FileName.Length-FileName.LastIndexOf(".")-1);
for (int i=0; i<AcceptedFileTypes.Length; i++) {
if (ext == AcceptedFileTypes[i]) {
return true;
}
}
return false;
}
</script>
<asp:panel id="MainPage" runat="server" visible="false">
<!doctype html public "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
<META HTTP-EQUIV="Expires" CONTENT="0">
<title>插入图片</title>
<style>
body {
margin: 0px 0px 0px 0px;
padding: 0px 0px 0px 0px;
background: #ffffff;
width: 100%;
overflow:hidden;
border: 0;
}
body,tr,td {
color: #000000;
font-family: Verdana, Arial, Helvetica, sans-serif;
font-size: 10pt;
}
div.imagespacer {
width: 120;
height: 126;
text-align: center;
float: left;
font: 10pt verdana;
margin: 5px;
overflow: hidden;
}
div.imageholder {
margin: 0px;
padding: 0px;
border: 1 solid #CCCCCC;
width: 100;
height: 100;
}
div.titleholder {
font-family: ms sans serif, arial;
font-size: 8pt;
width: 100;
text-overflow: ellipsis;
overflow: hidden;
white-space: nowrap;
}
</style>
<script language="javascript">
lastDiv = null;
function divClick(theDiv,filename) {
if (lastDiv) {
lastDiv.style.border = "1 solid #CCCCCC";
}
lastDiv = theDiv;
theDiv.style.border = "2 solid #316AC5";
document.getElementById("FileToDelete").value = filename;
}
function showimg(){
document.all.imgview.innerHTML="<img src='"+document.all.UploadFile.value+"'>";
}
function returnImage(imagename,width,height) {
var arr = new Array();
arr["filename"] = imagename;
arr["width"] = width;
arr["height"] = height;
window.parent.returnValue = arr;
window.parent.close();
}
</script>
</HEAD>
<body>
<table width=100% height=100% cellpadding=0 cellspacing=0 border=0>
<FORM encType="multipart/form-data" runat="server" ID="Form1">
<tr><td>
<div id="galleryarea" style="width=100%; height:100%; overflow: auto;">
<asp:label id="gallerymessage" runat="server"></asp:label>
<asp:panel id="GalleryPanel" runat="server"></asp:panel>
<span id="imgview"></span>
</div>
</td></tr>
<asp:Panel id="UploadPanel" runat="server">
<tr><td height=16 style="padding-left:10px;border-top: 1 solid #999999; background-color:#99ccff;">
<table>
<tr>
<td valign=top><input id="UploadFile" type="file" name="UploadFile" onchange="showimg()" runat="server" style="width:300;"/></td>
<td valign=top><asp:button id="UploadImage" Text="上传" runat="server" onclick="UploadImage_OnClick" /></td>
</tr>
<tr>
<td colspan=3>
<asp:RegularExpressionValidator runat="server"
ControlToValidate="UploadFile"
id="FileValidator" display="dynamic"/>
<asp:literal id="ResultsMessage" runat="server" />
</td>
</tr></table>
<input type="hidden" id="RootImagesFolder" Value="images" runat="server" NAME="RootImagesFolder"/>
</td></tr>
</asp:panel>
</form>
</table>
</body>
</HTML>
</asp:panel>
<asp:panel id="iframePanel" runat="server" >
<html>
<head><title>插入图片</title></head>
<style>
body {
margin: 0px 0px 0px 0px;
padding: 0px 0px 0px 0px;
background: #ffffff;
overflow:hidden;
}
</style>
<body>
<iframe style="width:100%;height:100%;border:0;" border=0 frameborder=0 src="ftb.imagegallery.aspx?frame=1&<%=Request.QueryString%>"></iframe>
</body>
</html>
</asp:panel>
用try catch 处理下 不知道可以不 。
<form action="servletName或者是StrutsActionName" enctype="MULTIPART/FORM-DATA" method=post> <br /> 上传文件名: <input type="text" name="uploadFile" /> <br /> 选择要上载的文件 <input type="file" name="filename" /> <br /> <input type="submit" value="上载" /> </form>
下面是两种类型的后台代码:
(1)后台是servlet的
import java.io.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.ServletInputStream; public class UpBean { public void doUpload(HttpServletRequest request) throws IOException { PrintWriter pw = new PrintWriter( new BufferedWriter(new FileWriter("test.txt"))); ServletInputStream in = request.getInputStream(); int i = in.read(); while (i != -1) { pw.print((char) i); i = in.read(); } pw.close(); } } (2)后台是struts
package fileupload;
import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import javax.servlet.ServletContext;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.util.ServletContextAware;
import com.opensymphony.xwork2.ActionSupport;
public class FileUploadAction extends ActionSupport implements ServletContextAware {
private static final long serialVersionUID = -5016873153441103539L;
private File doc;
private String fileName;
private String contentType;
private ServletContext context;
public void setDoc(File file) {
this.doc = file;
}
public void setDocFileName(String fileName) {
this.fileName = fileName;
}
public void setDocContentType(String contentType) {
this.contentType = contentType;
}
public void setServletContext(ServletContext context) {
this.context = context;
}
public String execute() throws Exception {
String targetDirectory = context.getRealPath("/upload");
String targetFileName = generateFileName(fileName);
File target = new File(targetDirectory, targetFileName);
FileUtils.copyFile(doc, target);
return SUCCESS;
}
private String generateFileName(String fileName) {
DateFormat format = new SimpleDateFormat("yyMMddHHmmss");
String formatDate = format.format(new Date());
int random = new Random().nextInt(10000);
int position = fileName.lastIndexOf(".");
String extension = fileName.substring(position);
return formatDate + random + extension;
}
}
希望能帮到你:-)
if (this.fu1.HasFile) {
HttpPostedFile hpf=this.fu1.PostedFile;
string filename =Path.GetFileName(hpf.FileName),extension=Path.GetExtension(hpf.FileName);
//判断格式
this.fu1.PostedFile.SaveAs("c:\\123.jpg");
}
}<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="a_Default" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>无标题页</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:FileUpload ID="fu1" runat="server" />
<asp:Button runat="server" ID="btnok" Text="Upload" OnClick="btnok_click" />
</div>
</form>
</body>
</html>