c#客户端图片上传到服务器端文件并且把路径保存到vs自带数据库
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c#客户端图片上传到服务器端文件并且把路径保存到vs自带数据库相关的知识,希望对你有一定的参考价值。
using System;using System.IO;
using System.Web.UI.HtmlControls;
namespace JH_ProfessionCMS.Common
/// <summary>
/// 功能 : 上传文件操作类
/// 作者 : xtx
/// </summary>
public class UpFile
public UpFile()
#region 是否允许该扩展名上传 IsAllowedExtension
/// <summary>
/// 是否允许该扩展名上传
/// </summary>
/// <paramname = "hifile">HtmlInputFile 控件 </param>
/// <returns> 允许则返回 true, 否则返回 false </returns>
public bool IsAllowedExtension(HtmlInputFile hifile)
string strOldFilePath = "";
string strExtension = "";
// 允许上传的扩展名,可以改成从配置文件中读出
string[]arrExtension = ".gif",".jpg",".jpeg",".bmp",".png";
if(hifile.PostedFile.FileName != string.Empty)
strOldFilePath = hifile.PostedFile.FileName;
// 取得上传文件的扩展名
strExtension = strOldFilePath.Substring(strOldFilePath.LastIndexOf("."));
// 判断该扩展名是否合法
for(int i = 0;i <arrExtension.Length;i++)
if(strExtension.Equals(arrExtension[i]))
return true;
return false;
#endregion
#region 判断上传文件大小是否超过最大值 IsAllowedLength
/// <summary>
/// 判断上传文件大小是否超过最大值
/// </summary>
/// <param name="hifile">HtmlInputFile 控件 </param>
/// <returns> 超过最大值返回 false, 否则返回 true. </returns>
public bool IsAllowedLength(HtmlInputFile hifile)
// 允许上传文件大小的最大值 , 可以保存在 xml 文件中 , 单位为 KB
int i = 20;
// 如果上传文件的大小超过最大值 , 返回 flase, 否则返回 true.
if(hifile.PostedFile.ContentLength > i * 1024)
return false;
return true;
#endregion
#region 获取一个不重复的文件名 GetUniqueString
/// <summary>
/// 获取一个不重复的文件名
/// </summary>
/// <returns> </returns>
public string GetUniqueString()
// 得到的文件名形如 :20050922101010
return DateTime.Now.ToString("yyyyMMddhhmmss");
#endregion
#region 删除指定文件 DeleteFile
/// <summary>
/// 删除指定文件
/// </summary>
/// <param name="strAbsolutePath"> 文件绝对路径 </param>
/// <param name="strFileName"> 文件名 </param>
public void DeleteFile(string strAbsolutePath, string strFileName)
// 判断路径最后有没有 \ 符号,没有则自动加上
if(strAbsolutePath.LastIndexOf("\\") == strAbsolutePath.Length)
// 判断要删除的文件是否存在
if(File.Exists(strAbsolutePath + strFileName))
// 删除文件
File.Delete(strAbsolutePath + strFileName);
else
if(File.Exists(strAbsolutePath + "\\" + strFileName))
File.Delete(strAbsolutePath + "\\" + strFileName);
#endregion
#region 上传文件并返回文件名 SaveFile
/// <summary>
/// 上传文件并返回文件名
/// </summary>
/// <param name="hifile">HtmlInputFile 控件 </param>
/// <param name="strAbsolutePath"> 绝对路径 . 如 :Server.MapPath(@"Image/upload") 与 Server.MapPath(@"Image/upload/") 均可 , 用 \ 符号亦可 </param>
/// <returns> 返回的文件名即上传后的文件名 </returns>
public string SaveFile(HtmlInputFile hifile,string strAbsolutePath)
string strOldFilePath = "",strExtension = "",strNewFileName = "";
// 如果上传文件的文件名不为空
if(hifile.PostedFile.FileName != string.Empty)
strOldFilePath = hifile.PostedFile.FileName;
// 取得上传文件的扩展名
strExtension = strOldFilePath.Substring(strOldFilePath.LastIndexOf("."));
// 文件上传后的命名
strNewFileName = GetUniqueString() + strExtension;
// 如果路径末尾为 \ 符号,则直接上传文件
if(strAbsolutePath.LastIndexOf("\\") == strAbsolutePath.Length)
hifile.PostedFile.SaveAs(strAbsolutePath + strNewFileName);
else
hifile.PostedFile.SaveAs(strAbsolutePath + "\\" + strNewFileName);
return strNewFileName;
#endregion
#region 重新上传文件,删除原有文件 CoverFile
/// <summary>
/// 重新上传文件,删除原有文件
/// </summary>
/// <param name="ffFile">HtmlInputFile 控件 </param>
/// <param name="strAbsolutePath"> 绝对路径 . 如 :Server.MapPath(@"Image/upload") 与 Server.MapPath(@"Image/upload/") 均可 , 用 \ 符号亦可 </param>
/// <param name="strOldFileName"> 旧文件名 </param>
public string CoverFile(HtmlInputFile ffFile,string strAbsolutePath,string strOldFileName)
// 获得新文件名
string strNewFileName = GetUniqueString();
if(ffFile.PostedFile.FileName != string.Empty)
// 旧图片不为空时先删除旧图片
if(strOldFileName != string.Empty)
DeleteFile(strAbsolutePath,strOldFileName);
return SaveFile(ffFile,strAbsolutePath);
return "";
#endregion
至于保存嘛,简单了,上面已经有取得路径的代码。你把数据库操作加进去就行了。 参考技术A 这样
string names = fupImg.FileName.ToString();
fupImg.SaveAs(Server.MapPath("img/") + names);
names就可以保存到数据库中了
h5 端图片上传-模拟多张上传
1、由于后端的限制,上传图片到服务器只能的一张一张传
2、显示图片预览是本地的图片
3、根据服务器返回的结果拿到相应的路径保存到提交评论的接口中
4、删除的时候,需要删除对应的路径,不要把删除的提交到评论的接口中
A、comment-detail.js
var status = common.getQueryStr("status"); var subsId = common.getQueryStr("subsId"); var isList = common.getQueryStr("isList"); var prodId = common.getQueryStr("prodId"); var CommentDetail = { point : 5, commentCon: ‘‘, uploadImg:[], everyUploadCount:0, layerLoadingIndex:null, submitComment : function (param) { var obj = param.obj; obj.click(function(){ var url = ‘/app/comment‘; if(CommentDetail.commentCon.length<10){ alert("文字最少限制10字"); return; } if(CommentDetail.commentCon.length>500){ alert("文字最多限制500字"); return; } var imagesUrl = ‘‘; for(var i=0;i<CommentDetail.uploadImg.length;i++){ if(i==CommentDetail.uploadImg.length-1){ imagesUrl += CommentDetail.uploadImg[i].savepath; }else{ imagesUrl += CommentDetail.uploadImg[i].savepath +‘,‘; } } var params = { "reqBody":{ "bossProdId" : prodId, "content" : CommentDetail.commentCon, "subsId" : subsId, "score" : CommentDetail.point, "images": imagesUrl } } common.ajax("POST",url,params,null,function (ret) { if(ret.resultCode==0){ alertDialog(‘提交成功‘,function () { $("#go-to-back").click(); }); } }); }); }, imgFileUpload : function () { var input = document.getElementById("imgFileUpload"); var result,div; if(typeof FileReader===‘undefined‘){ result.innerHTML = "抱歉,你的浏览器不支持 FileReader"; input.setAttribute(‘disabled‘,‘disabled‘); }else{ input.addEventListener(‘change‘,readFile,false); } function readFile(){ var files = this.files; var liLength= $("#commentImgList li.li-img").length; var count = files.length>6-liLength ? 6-liLength : files.length; CommentDetail.everyUploadCount = count; CommentDetail.layerLoadingIndex = layer.open({ type: 2 ,content: ‘加载中‘ ,shadeClose:false }); for(var i=0;i<count;i++){ if (!input[‘value‘].match(/.jpg|.gif|.png|.bmp/i)){ return alert("上传的图片格式不正确,请重新选择") } var item = files[i]; (function(img) { var mpImg = new MegaPixImage(img); var resImg = document.createElement("img"); var items = item; resImg.file = img; mpImg.render(resImg, { maxWidth: 1280, maxHeight: 960, quality: 1 }, function() { var wdh = Number(resImg.width)>Number(resImg.height)? true : false; var commentListLiHeight = Number((window.screen.width)*0.92*0.3).toFixed(1); if(wdh){ var htmlStr = ‘<li class="li-img"><a style="height: ‘+commentListLiHeight+‘px" href="javascript:;"><img src="‘+resImg.src+‘" class="dataImg" onclick="CommentDetail.initSwiper(this)" style="width: 100%;"></a><i class="icon-del" onclick="CommentDetail.delImage(this,\‘‘+items.name+‘\‘)"></i></li>‘ }else{ var htmlStr = ‘<li class="li-img"><a style="height: ‘+commentListLiHeight+‘px" href="javascript:;"><img src="‘+resImg.src+‘" class="dataImg" onclick="CommentDetail.initSwiper(this)" style="height: 100%;"></a><i class="icon-del" onclick="CommentDetail.delImage(this,\‘‘+items.name+‘\‘)"></i></li>‘ } $("#commentImgList").prepend(htmlStr); CommentDetail.uploadShowHide(); CommentDetail.fileUpload(resImg.src, item.type,items.name); }); })(item); } } }, fileUpload: function(data,type,name) { var opts = { ‘file‘:name.slice(0,name.lastIndexOf(‘.‘)), ‘url‘:"/js/ueditor/jsp/uploader.jsp?action=uploaduser&dirName=comment&needCompress=true" }; if(type.indexOf(‘jpeg‘)>-1) type=‘image/jpg‘; var text = window.atob(data.split(‘,‘)[1]); var ia = new Uint8Array(text.length); for (var i = 0; i < data.length; i++) { ia[i] = text.charCodeAt(i); }; var Builder = window.WebKitBlobBuilder || window.MozBlobBuilder; var blob; if (Builder) { var builder = new Builder(); builder.append(ia); blob = builder.getBlob(type); } else { blob = new window.Blob([ia], {type: type}); } var fd = new FormData(); fd.append(opts.file, blob); var xhr = new XMLHttpRequest(); xhr.addEventListener("load", opts.success, false); xhr.addEventListener("error", opts.error, false); xhr.open("POST", opts.url); xhr.send(fd); xhr.onreadystatechange = function () { if (xhr.readyState == 4 && xhr.status == 200) { CommentDetail.everyUploadCount--; var ret = JSON.parse(xhr.responseText); console.log(ret); console.log(ret.state); if(ret.state==‘SUCCESS‘){ CommentDetail.uploadImg.push({"original":ret.original,"savepath":ret.savepath}); } if(CommentDetail.everyUploadCount==0){ layer.close(CommentDetail.layerLoadingIndex); } } }; }, delImage : function(obj,name){ console.log(‘删除前:‘,CommentDetail.uploadImg) for(var i=0;i<CommentDetail.uploadImg.length;i++){ var original = CommentDetail.uploadImg[i].original.slice(0,CommentDetail.uploadImg[i].original.lastIndexOf(‘.‘)); var delName = name.slice(0,name.lastIndexOf(‘.‘)); if(original == delName){ CommentDetail.uploadImg.splice(i,1); } } console.log(‘删除后:‘,CommentDetail.uploadImg) $(obj).parents(‘li‘).remove(); CommentDetail.uploadShowHide(); }, initSwiper : function (obj) { var img = $("#commentImgList").find(‘.li-img‘).find(‘img‘); var index = $(obj).parents(‘li.li-img‘).index(); var html = ‘‘; html += ‘<div class="swiper-container swiper-container-comment" id="swiperContainer" style="display:block;"><div class="swiper-wrapper">‘; for(var i=0;i<img.length;i++){ html += ‘<div class="swiper-slide ui-flex justify-center center">‘ + ‘<img src="‘+img[i].src+‘" onclick="CommentDetail.closeSwiper()">‘ + ‘</div>‘; } html += ‘</div><div class="swiper-pagination"></div></div>‘; $(‘body‘).append(html); new Swiper (‘#swiperContainer‘, { loop: true, initialSlide:index, pagination: ‘.swiper-pagination‘, paginationType : ‘fraction‘ }) }, closeSwiper : function () { $("#swiperContainer").remove(); }, }; $(function () { CommentDetail.submitComment({obj:$("#btnSubmitComment")}); CommentDetail.imgFileUpload() });
B、HTML
<ul class="list" id="commentImgList" data-pswp-uid="1"> <li class="li-file"> <img src="images/input-file-default.png" style="width:100%;"> <input type="file" class="img-file" id="imgFileUpload" multiple/> </li> </ul> <a href="javascript:;" class="btn-submit" id="btnSubmitComment">提交</a>
C、megapix-image.js (https://github.com/stomita/ios-imagefile-megapixel)
/** * Mega pixel image rendering library for iOS6 Safari * * Fixes iOS6 Safari‘s image file rendering issue for large size image (over mega-pixel), * which causes unexpected subsampling when drawing it in canvas. * By using this library, you can safely render the image with proper stretching. * * Copyright (c) 2012 Shinichi Tomita <[email protected]> * Released under the MIT license */ (function() { /** * Detect subsampling in loaded image. * In iOS, larger images than 2M pixels may be subsampled in rendering. */ function detectSubsampling(img) { var iw = img.naturalWidth, ih = img.naturalHeight; if (iw * ih > 1024 * 1024) { // subsampling may happen over megapixel image var canvas = document.createElement(‘canvas‘); canvas.width = canvas.height = 1; var ctx = canvas.getContext(‘2d‘); ctx.drawImage(img, -iw + 1, 0); // subsampled image becomes half smaller in rendering size. // check alpha channel value to confirm image is covering edge pixel or not. // if alpha value is 0 image is not covering, hence subsampled. return ctx.getImageData(0, 0, 1, 1).data[3] === 0; } else { return false; } } /** * Detecting vertical squash in loaded image. * Fixes a bug which squash image vertically while drawing into canvas for some images. */ function detectVerticalSquash(img, iw, ih) { var canvas = document.createElement(‘canvas‘); canvas.width = 1; canvas.height = ih; var ctx = canvas.getContext(‘2d‘); ctx.drawImage(img, 0, 0); var data = ctx.getImageData(0, 0, 1, ih).data; // search image edge pixel position in case it is squashed vertically. var sy = 0; var ey = ih; var py = ih; while (py > sy) { var alpha = data[(py - 1) * 4 + 3]; if (alpha === 0) { ey = py; } else { sy = py; } py = (ey + sy) >> 1; } var ratio = (py / ih); return (ratio===0)?1:ratio; } /** * Rendering image element (with resizing) and get its data URL */ function renderImageToDataURL(img, options, doSquash) { var canvas = document.createElement(‘canvas‘); renderImageToCanvas(img, canvas, options, doSquash); return canvas.toDataURL("image/jpeg", options.quality || 0.8); } /** * Rendering image element (with resizing) into the canvas element */ function renderImageToCanvas(img, canvas, options, doSquash) { var iw = img.naturalWidth, ih = img.naturalHeight; if (!(iw+ih)) return; var width = options.width, height = options.height; var ctx = canvas.getContext(‘2d‘); ctx.save(); transformCoordinate(canvas, ctx, width, height, options.orientation); var subsampled = detectSubsampling(img); if (subsampled) { iw /= 2; ih /= 2; } var d = 1024; // size of tiling canvas var tmpCanvas = document.createElement(‘canvas‘); tmpCanvas.width = tmpCanvas.height = d; var tmpCtx = tmpCanvas.getContext(‘2d‘); var vertSquashRatio = doSquash ? detectVerticalSquash(img, iw, ih) : 1; var dw = Math.ceil(d * width / iw); var dh = Math.ceil(d * height / ih / vertSquashRatio); var sy = 0; var dy = 0; while (sy < ih) { var sx = 0; var dx = 0; while (sx < iw) { tmpCtx.clearRect(0, 0, d, d); tmpCtx.drawImage(img, -sx, -sy); ctx.drawImage(tmpCanvas, 0, 0, d, d, dx, dy, dw, dh); sx += d; dx += dw; } sy += d; dy += dh; } ctx.restore(); tmpCanvas = tmpCtx = null; } /** * Transform canvas coordination according to specified frame size and orientation * Orientation value is from EXIF tag */ function transformCoordinate(canvas, ctx, width, height, orientation) { switch (orientation) { case 5: case 6: case 7: case 8: canvas.width = height; canvas.height = width; break; default: canvas.width = width; canvas.height = height; } switch (orientation) { case 2: // horizontal flip ctx.translate(width, 0); ctx.scale(-1, 1); break; case 3: // 180 rotate left ctx.translate(width, height); ctx.rotate(Math.PI); break; case 4: // vertical flip ctx.translate(0, height); ctx.scale(1, -1); break; case 5: // vertical flip + 90 rotate right ctx.rotate(0.5 * Math.PI); ctx.scale(1, -1); break; case 6: // 90 rotate right ctx.rotate(0.5 * Math.PI); ctx.translate(0, -height); break; case 7: // horizontal flip + 90 rotate right ctx.rotate(0.5 * Math.PI); ctx.translate(width, -height); ctx.scale(-1, 1); break; case 8: // 90 rotate left ctx.rotate(-0.5 * Math.PI); ctx.translate(-width, 0); break; default: break; } } var URL = window.URL && window.URL.createObjectURL ? window.URL : window.webkitURL && window.webkitURL.createObjectURL ? window.webkitURL : null; /** * MegaPixImage class */ function MegaPixImage(srcImage) { if (window.Blob && srcImage instanceof Blob) { if (!URL) { throw Error("No createObjectURL function found to create blob url"); } var img = new Image(); img.src = URL.createObjectURL(srcImage); this.blob = srcImage; srcImage = img; } if (!srcImage.naturalWidth && !srcImage.naturalHeight) { var _this = this; srcImage.onload = srcImage.onerror = function() { var listeners = _this.imageLoadListeners; if (listeners) { _this.imageLoadListeners = null; for (var i=0, len=listeners.length; i<len; i++) { listeners[i](); } } }; this.imageLoadListeners = []; } this.srcImage = srcImage; } /** * Rendering megapix image into specified target element */ MegaPixImage.prototype.render = function(target, options, callback) { if (this.imageLoadListeners) { var _this = this; this.imageLoadListeners.push(function() { _this.render(target, options, callback); }); return; } options = options || {}; var imgWidth = this.srcImage.naturalWidth, imgHeight = this.srcImage.naturalHeight, width = options.width, height = options.height, maxWidth = options.maxWidth, maxHeight = options.maxHeight, doSquash = !this.blob || this.blob.type === ‘image/jpeg‘; if (width && !height) { height = (imgHeight * width / imgWidth) << 0; } else if (height && !width) { width = (imgWidth * height / imgHeight) << 0; } else { width = imgWidth; height = imgHeight; } if (maxWidth && width > maxWidth) { width = maxWidth; height = (imgHeight * width / imgWidth) << 0; } if (maxHeight && height > maxHeight) { height = maxHeight; width = (imgWidth * height / imgHeight) << 0; } var opt = { width : width, height : height }; for (var k in options) opt[k] = options[k]; var tagName = target.tagName.toLowerCase(); if (tagName === ‘img‘) { target.src = renderImageToDataURL(this.srcImage, opt, doSquash); } else if (tagName === ‘canvas‘) { renderImageToCanvas(this.srcImage, target, opt, doSquash); } if (typeof this.onrender === ‘function‘) { this.onrender(target); } if (callback) { callback(); } if (this.blob) { this.blob = null; URL.revokeObjectURL(this.srcImage.src); } }; /** * Export class to global */ if (typeof define === ‘function‘ && define.amd) { define([], function() { return MegaPixImage; }); // for AMD loader } else if (typeof exports === ‘object‘) { module.exports = MegaPixImage; // for CommonJS } else { this.MegaPixImage = MegaPixImage; } })();
以上是关于c#客户端图片上传到服务器端文件并且把路径保存到vs自带数据库的主要内容,如果未能解决你的问题,请参考以下文章
c# WinForm中上传一个图片到服务器,然后把服务器的相对路径存入数据库中