html+js上传文件
WEB页面开发功能中,需要用到一个图片上传功能,页面选择图片,上传并保存到后台,页面图片上传后,得到一个URL,把URL存入数据库中
html代码
HTML 全选
<label type="button" class="btn btn-primary m-0" for="selectImage">选择图片</label>
<input id="selectImage" type="file" accept=".png,.jpg,.jpeg" style="display:none;">
JS代码
JavaScript 全选
$(`input[type="file"]`).change(function(){
var files = $(this).prop('files')
var type = $(this).data("type")
if (files.length > 0) {
file = files[0];
if (isImageFile(file)) {
var reader = new FileReader();
reader.onload = () => {
//$("#img-background").attr("src", reader.result);
upLoadH5Img(reader.result,type)
reader.onload = null;
};
reader.readAsDataURL(file);
}
}
})
// 判断文件是否是图片
function isImageFile(file) {
if (file.type) {
return /^image\/\w+$/.test(file.type);
} else {
return /\.(jpg|jpeg|png|gif)$/.test(file);
}
};
function upLoadH5Img(base64,tukutype) {
var url='/api/uploadheadimg'
// 方法2:上传oos
const xhr = new XMLHttpRequest()
xhr.withCredentials = false
xhr.open('POST', url)
// xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded;charset=utf-8')
//xhr.setRequestHeader('x-token', this.$store.getters.token)
xhr.upload.onprogress = function (e) {
//progress(e.loaded / e.total * 100)
}
xhr.onload = function () {
if (xhr.status === 403) {
failure('HTTP Error: ' + xhr.status, { remove: true })
return
}
if (xhr.status < 200 || xhr.status >= 300) {
failure('HTTP Error: ' + xhr.status)
return
}
const json = JSON.parse(xhr.responseText)
if (!json || typeof json.url !== 'string') {
failure('Invalid JSON: ' + xhr.responseText)
return
}
//const file = json.data
//const url = '/purchase/manage/attachment/public/operation/pull?path=' + file.fileName + '&fileName=' +
// encodeURIComponent(file.originalFileName)
$("#url").val(json.url)
}
xhr.onerror = function () {
failure('Image upload failed due to a XHR Transport error. Code: ' + xhr.status)
}
var v = convertBase64ToBlob(base64);
const formData = new FormData()
formData.append('file', v, 'img.jpeg')
xhr.send(formData)
}
JS通用上传函数
JavaScript 全选
function UploadImg(url,file,callback_success,callback_error){
// 方法2:上传oos
const xhr = new XMLHttpRequest()
xhr.withCredentials = false
xhr.open('POST', url)
//xhr.upload.onprogress = function (e) {
// progress(e.loaded / e.total * 100)
//}
xhr.onload = function() {
if (xhr.status != 200) {
if(callback_error)
callback_error('HTTP Error: ' + xhr.status)
return
}
const json = JSON.parse(xhr.responseText)
if (!json || typeof json.url !== 'string') {
if(callback_error)
callback_error('Invalid JSON: ' + xhr.responseText)
return
}
// 上传成功回调
if(callback_success) callback_success(json.url)
}
xhr.onerror = function() {
if(callback_error)
callback_error('图片上传失败 HTTP Error: ' + xhr.status)
}
const formData = new FormData()
formData.append('file', file, file.name)
xhr.send(formData)
}
使用:
JavaScript 全选
$("#selectImage").change(function () {
var files = $(this).prop('files')
if (files.length > 0) {
file = files[0];
if (isImageFile(file)) {
var upload_url = '/uploadurl'
UploadImg(upload_url, file, (url) => {
console.log('图片URL地址:' + url)
}, (err) => {
GZDialog.alert(err)
})
}
// 清除选择
$("#selectImage")[0].value = null;
}
})
C#上传代码实现
C# 全选
using (OpenFileDialog openFileDialog = new OpenFileDialog())
{
openFileDialog.Filter = "(*.jpg,*.png,*.jpeg,*.bmp,*.gif)|*.jgp;*.png;*.jpeg;*.bmp;*.gif";
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
string url = txt_host.Text + "/api/upload/" + cmb_Type.SelectedValue;
RestClient client = new RestClient(url);
client.Timeout = -1;
var request = new RestRequest(Method.POST);
foreach (var v in cookies)
{
request.AddParameter(v.Name, v.Value, ParameterType.Cookie);
}
string imgFileName = openFileDialog.FileName;
//string imgName = System.IO.Path.GetFileName(imgFileName);
request.AddFile("file", imgFileName);
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
}
}
后台API代码
C# 全选
[HttpPost]
public HDFile ArticleImageNoMask(IFormFile file, bool compression = false)
{
string dir = PathProvider.GetRootArticleImage();
var data = SaveImage(file, dir, false, compression);
var tag = "article_image";
AddDB(data, tag);
return new HDFile(data.fileName, $"/images/{tag}/{data.fileName}", "");
}
ImageInfoModel SaveImage(IFormFile file, string dir, bool enableImageMask, bool compression = true)
{
//如果路径不存在,创建路径
if (!Directory.Exists(dir))
Directory.CreateDirectory(dir);
ImageInfoModel data = new ImageInfoModel();
data.relativePath = RelativePath(dir);
var strDateTime = DateTime.Now.ToString("yyMMddhhmmssfff"); //取得时间字符串
var strRan = Convert.ToString(new Random().Next(100, 999)); //生成三位随机数
data.fileID = strDateTime + strRan;
using (var memoryStream = new MemoryStream())
{
file.CopyTo(memoryStream);
using (var img = Image.FromStream(memoryStream))
{
//文件后缀
data.extension = "." + img.RawFormat.ToString().ToLower();
string filename = dir + "\\" + data.fileName;
img.Save(filename);
}
}
return data;
}
public class HDFile
{
public HDFile(string name, string url, string size)
{
Name = name;
Url = url;
Size = size;
}
public string Name { get; set; }
public string Url { get; set; }
public string Size { get; set; }
}
版权声明:本文为YES开发框架网发布内容,转载请附上原文出处连接
post 管理员