如何用jsp把客户端的文件上传到服务器什么去????把文件保存在服务器什么的一个指定目录下面
String path = getServletContext()getRealPath("/");
try {
BufferedInputStream bis = new BufferedInputStream(requestgetInputStream());
//创建临时文件
RandomAccessFile raf = new RandomAccessFile(path + "image//tempjpg", "rw");
byte b[] = new byte[1000];
int n;
while ((n = bisread(b)) != -1) {
rafwrite(b, 0, n);
}
bisclose();
rafseek(0);
for (int i = 0; i < 4; i++) {
rafreadLine();
}
long begin = rafgetFilePointer();
long m = raflength() - 1;
rafseek(m);
for (int i = 0; m >= 0 && (n = rafreadByte()) != -1 && i < 2;) {
if (n == '\n') {
i++;
}
rafseek(m = rafgetFilePointer() - 2);
}
long end = rafgetFilePointer();
RandomAccessFile raf2 = new RandomAccessFile(path + "image//" + id + "jpg", "rw");
rafseek(begin);
for (long i = begin; i < end; i++) {
raf2write(rafreadByte());
}
rafclose();
raf2close();
//删除临时文件
File temp=new File(path+"image//tempjpg");
tempdelete();
sessionremoveAttribute("photo");
outprint("<script>alert('更新成功');");//仍需刷新
outprint("windowlocation='Admin_view_bookjspid=" + id + "';</script>");
} catch (Exception e) {
eprintStackTrace();
outprint("<script>alert('出现错误');historyback();</script>");
}
我是来收分的
客户端
<input type="file" name="upfile" />
服务端代码
HttpPostedFile oFile = RequestFiles["upfile"]; //这里的"upfile"要和客户端type="file"的name一致
string sFilePath = "服务器端的绝对路径";
oFileSaveAs(sFilePath); //将上传的文件保存到 指定的路径
===========================================
为何要将type="file" 隐藏?
只有当你从type="file"点“浏览”选择要上传的文件后,执行form的post提交在服务端才能收到type="file"上传上来的数据啊
C#使用webservice把文件上传到服务器的代码如下(这里以C:\\zhidaojpg这个文件上传为例):
WebService部分:
/// <summary>/// 保存文件到远程服务器
/// </summary>
/// <param name="FileByteArray">待转换字节数组</param>
/// <param name="FileLength">字节长度</param>
/// <param name="SaveToUrl">保存路径</param>
/// <returns>返回是否执行成功</returns>
[WebMethod(Description = "保存文件到远程服务器")]
public bool SaveFile(byte[] FileByteArray,int FileLength, string SaveToUrl)
{
try
{
FileStream fs = new FileStream(SaveToUrl, FileModeOpenOrCreate, FileAccessWrite);
fsWrite(FileByteArray, 0, FileLength);
fsClose();
}
catch {
return false;
}
return true;
}
上传文件调用部分:
protected void Button1_Click(object sender, EventArgs e){
MangerPhotoService mp = new MangerPhotoService();
ResponseWrite(mpSaveFile(getByte(), FileUpload1PostedFileContentLength, "C:\\zhidaojpg"));
} private byte[] getByte() {//获得转化后的字节数组
//得到用户要上传的文件名
string strFilePathName = FileUpload1PostedFileFileName;
string strFileName = PathGetFileName(strFilePathName);
int FileLength = FileUpload1PostedFileContentLength;
//上传文件
Byte[] FileByteArray = new Byte[FileLength]; //图象文件临时储存Byte数组
Stream StreamObject = FileUpload1PostedFileInputStream; //建立数据流对像
//读取图象文件数据,FileByteArray为数据储存体,0为数据指针位置、FileLnegth为数据长度
StreamObjectRead(FileByteArray, 0, FileLength);
return FileByteArray;
}
0条评论