最近工作需要,从本地上传文件到服务器,同时提供下载功能到本地,,这里贴下代码,,不多说。
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using dataGridAndWebApi.Models;
using System.IO;
namespace dataGridAndWebApi.Controllers
{
public class uploadController : ApiController
{
DataClasses1DataContext gdc = new DataClasses1DataContext();
//保存文件至 数据库
[HttpPost]
public IHttpActionResult saveUrl()
{
try
{
HttpFileCollection files = HttpContext.Current.Request.Files;
foreach (string key in files.AllKeys)
{
HttpPostedFile file = files[key];//file.ContentLength文件长度
var ee = file.InputStream;
byte[] byts = new byte[ee.Length];
ee.Read(byts, 0, byts.Length);
string reqs = Encoding.Default.GetString(byts);
var esw = Convert.ToBase64String(byts);
var fileType = file.ContentType;
if (fileType.Substring(0, fileType.IndexOf("/")).Equals("iamges"))
{
var dataHeader = "data:" + file.ContentType + ";base64,";
esw += dataHeader;
}
FileUpAndDownTest ft = new FileUpAndDownTest();
ft.FileData = esw;
ft.FileName = file.FileName;
ft.FileType = fileType;
gdc.FileUpAndDownTest.InsertOnSubmit(ft);
gdc.SubmitChanges();
}
return Ok("success2");
}
catch (Exception)
{
return BadRequest();
}
}
//获得数据库的文件信息
[HttpGet]
public IHttpActionResult getAllCitys()
{
var getall = (from n in gdc.FileUpAndDownTest
select new {n.id, n.FileName, n.FileType}
).ToList();
return Json(getall);
}
//下载
[System.Web.Http.Route("api/downloadFile/{id}")]
[HttpGet]
public void downloadFile(int id)
{
var thisFile = (from a in gdc.FileUpAndDownTest
where a.id == id
select a
).First();
if (thisFile != null)
{
byte[] buffer = Convert.FromBase64String(thisFile.FileData);
Stream iStream = new System.IO.MemoryStream(buffer);
try
{
int length;
long dataToRead;
string filename = thisFile.FileName;
dataToRead = iStream.Length;
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.ContentType = thisFile.FileType; //文件类型
HttpContext.Current.Response.AddHeader("Content-Length", dataToRead.ToString());//添加文件长度,进而显示进度
//HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(filename, Encoding.UTF8));
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + filename);
while (dataToRead > 0)
{
if (HttpContext.Current.Response.IsClientConnected)
{
if ((dataToRead / 1000) < 1)
{
length = iStream.Read(buffer, 0, (int)dataToRead);
}
else
{
length = iStream.Read(buffer, 0, 1000);
}
HttpContext.Current.Response.OutputStream.Write(buffer, 0, length);
HttpContext.Current.Response.Flush();
buffer = new Byte[1000];
dataToRead = dataToRead - length;
}
else
{
dataToRead = -1;
}
}
}
catch (Exception ex)
{
HttpContext.Current.Response.Write("文件下载时出现错误!");
}
finally
{
if (iStream != null)
{
iStream.Close();
}
//结束响应,否则将导致网页内容被输出到文件,进而文件无法打开
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
}
}
}
}
}
testupload.component.ts
import { Component, OnInit } from '@angular/core';
import { FileInfo, FileRestrictions, RemoveEvent, SelectEvent, ClearEvent } from '@progress/kendo-angular-upload';
import { Observable } from 'rxjs/Observable';
import {Http} from '@angular/http';
import { SelectableSettings } from '@progress/kendo-angular-grid';
import * as $ from 'jquery';
@Component({
selector: 'app-testupload',
templateUrl: './testupload.component.html',
styleUrls: ['./testupload.component.scss']
})
export class TestuploadComponent {
public events: string[] = [];
public imagePreviews: FileInfo[] = [];
public uploadRemoveUrl: string = 'removeUrl';
// public uploadRestrictions: FileRestrictions = {
// allowedExtensions: ['.jpg', '.png']
// };
public uploadSaveUrl: string = '/api/upload';
private griddata: Array<any>;
private mySelection: number[] = [];
private selectgridcell: any;
private selectableSettings: SelectableSettings= {
mode: 'single'
};
private thisUrl = 'http://localhost:4200/api/downloadFile/';
constructor(private http: Http) {
this.getgriddata();
}
public getgriddata(){
this.http.get('/api/upload')
.map((res) => res.json())
.subscribe(data => this.griddata = data);
}
public clearEventHandler(e: ClearEvent): void {
this.log('Clearing the file upload');
this.imagePreviews = [];
}
public completeEventHandler() {
this.log(`All files processed`);
}
public removeEventHandler(e: RemoveEvent): void {
this.log(`Removing ${e.files[0].name}`);
let index = this.imagePreviews.findIndex(item => item.uid === e.files[0].uid);
if (index >= 0) {
this.imagePreviews.splice(index, 1);
}
}
public selectEventHandler(e: SelectEvent): void {
const that = this;
e.files.forEach((file) => {
that.log(`File selected: ${file.name}`);
if (!file.validationErrors) {
let reader = new FileReader();
reader.onload = function (ev) {
const image = {
name: reader.result,
uid: file.uid
};
that.imagePreviews.unshift(image);
};
reader.readAsDataURL(file.rawFile);
}
});
}
private log(event: string): void {
this.events.unshift(`${event}`);
}
// 选择时调用方法
onSelectedKeysChange(e) {
this.selectgridcell = this.griddata[this.mySelection[0]];
}
// getfile() {
// // let a = document.createElement('a');
// // const url = this.selectgridcell.FileData;
// // const filename = this.selectgridcell.FileName;
// // // data:image/jpg;base64,
// // a.href = 'data:' + this.selectgridcell.FileType + ';base64,' + url;
// // a.download = filename;
// // $('body').append(a); // 修复firefox中无法触发click
// // a.click();
// // $(a).remove();
// this.http.put('/api/upload', this.selectgridcell.id)
// .subscribe();
// }
}
testupload.component.html
<kendo-grid
[kendoGridBinding]="griddata"
[selectable]="selectableSettings"
[pageSize]="5"
[selectedKeys]="mySelection"
[kendoGridSelectBy]="id"
(selectedKeysChange)="onSelectedKeysChange($event)"
[pageable]="true" >
<kendo-grid-column field="id" title="ID" >
</kendo-grid-column>
<kendo-grid-column field="FileName" title="Name" >
</kendo-grid-column>
<kendo-grid-column field="FileType" title="Category">
</kendo-grid-column>
<kendo-grid-column title="Download" width="250">
<ng-template kendoGridCellTemplate let-dataItem>
<a [href]="thisUrl+dataItem.id">↓</a>
</ng-template>
</kendo-grid-column>
</kendo-grid>
<kendo-upload
[autoUpload]="false"
[saveUrl]="uploadSaveUrl"
[removeUrl]="uploadRemoveUrl"
(select)="selectEventHandler($event)"
(remove)="removeEventHandler($event)"
(complete)="completeEventHandler($event)"
[showFileList]="true"
[multiple]="false">
<kendo-upload-messages
select="Upload"
>
</kendo-upload-messages>
</kendo-upload>
<div *ngIf="imagePreviews.length" class="img-preview example-config">
<h3>Preview selected images</h3>
<img *ngFor="let image of imagePreviews"
[src]="image.name"
alt="image preview"
style="width: 200px; margin: 10px;" />
</div>
<span>{{image.name}}</span>
里面主要使用的是kendo grid ,upload. download使用的是C#提供的下载方法,非前台下载