C#使用webservice把文件上传到服务器
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;
}
//文件写入流
private void ReadFile()
{
Byte[] MesageFile;
string path =@"c:\123XML";
FileStream stream = new FileStream(path, FileModeOpen, FileAccessRead);
int size = ConvertToInt32(streamLength);
MesageFile = new Byte[size];
streamRead(MesageFile, 0, size);
streamClose()
string fileName =pathSubstring(pathLastIndexOf("\\") + 1, pathLength pathLastIndexOf("\\") - 1);
WriteFile(MesageFile, fileName);
}
//写入文件
private void WriteFile(Byte[] fileByte,string fileName)
{
string path = AppDomainCurrentDomainBaseDirectory + "\\UpLoad\\" + DateTimeNowToString("yyyy-MM-dd")+"\\";
if (!DirectoryExists(path))
DirectoryCreateDirectory(path);
string savepath = path + fileName;
FileStream fos = new FileStream(savepath, FileModeOpenOrCreate, FileAccessReadWrite);
fosWrite(MesageFile, 0, MesageFileLength);
fosClose();
}
上传的文件格式不限。
我们使用一些已有的组件帮助我们实现这种上传功能。
常用的上传组件:
Apache 的 Commons FileUpload
JavaZoom的UploadBean
jspSmartUpload
以下,以FileUpload为例讲解
1、在jsp端
<form id="form1" name="form1" method="post" action="servlet/fileServlet" enctype="multipart/form-data">
要注意enctype="multipart/form-data"
然后只需要放置一个file控件,并执行submit操作即可
<input name="file" type="file" size="20" >
<input type="submit" name="submit" value="提交" >
2、web端
核心代码如下:
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
requestsetCharacterEncoding("UTF-8");
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List items = uploadparseRequest(request);
Iterator itr = itemsiterator();
while (itrhasNext()) {
FileItem item = (FileItem) itrnext();
if (itemisFormField()) {
Systemoutprintln("表单参数名:" + itemgetFieldName() + ",表单参数值:" + itemgetString("UTF-8"));
} else {
if (itemgetName() != null && !itemgetName()equals("")) {
Systemoutprintln("上传文件的大小:" + itemgetSize());
Systemoutprintln("上传文件的类型:" + itemgetContentType());
Systemoutprintln("上传文件的名称:" + itemgetName());
File tempFile = new File(itemgetName());
File file = new File(scgetRealPath("/") + savePath, tempFilegetName());
itemwrite(file);
requestsetAttribute("uploadmessage", "上传文件成功!");
}else{
requestsetAttribute("uploadmessage", "没有选择上传文件!");
}
}
}
}catch(FileUploadException e){
eprintStackTrace();
} catch (Exception e) {
eprintStackTrace();
requestsetAttribute("uploadmessage", "上传文件失败!");
}
requestgetRequestDispatcher("/uploadResultjsp")forward(request, response);
}
package comletvdircloudutil;import comletvdircloudcontrollerDirectorWatermarkController;import orgslf4jLogger;import orgslf4jLoggerFactory;import javaio;import javanetHttpURLConnection;import javanetMalformedURLException;import javanetURL;/ Created by xijunge on 2016/11/24 0024 /public class HttpRequesterFile { private static final Logger log = LoggerFactorygetLogger(HttpRequesterFileclass); private static final String TAG = "uploadFile"; private static final int TIME_OUT = 100 1000; // 超时时间 private static final String CHARSET = "utf-8"; // 设置编码 / 上传文件到服务器 @param file 需要上传的文件 @param RequestURL 文件服务器的rul @return 返回响应的内容 / public static String uploadFile(File file, String RequestURL) throws IOException {
String result = null;
String BOUNDARY = "letv"; // 边界标识 随机生成 String PREFIX = "--", LINE_END = "\r\n";
String CONTENT_TYPE = "multipart/form-data"; // 内容类型 try {
URL url = new URL(RequestURL);
HttpURLConnection conn = (HttpURLConnection) urlopenConnection();
connsetReadTimeout(TIME_OUT);
connsetConnectTimeout(TIME_OUT);
connsetDoInput(true); // 允许输入流 connsetDoOutput(true); // 允许输出流 connsetUseCaches(false); // 不允许使用缓存 connsetRequestMethod("POST"); // 请求方式 connsetRequestProperty("Charset", CHARSET); // 设置编码 connsetRequestProperty("connection", "keep-alive");
connsetRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);
0条评论