react ts 上传

public MessageObjectPO<UploadPO> OnPostUpload(UploadRO uploadRO) {
            var response = new MessageObjectPO<UploadPO>();
            Guid guid = Guid.NewGuid();
            string FilePath = _serverSettings.SafetyRuleTempPath + "\\" + guid + "\\";
            DirectoryInfo di = new DirectoryInfo(FilePath);
            if (!di.Exists) {
                di.Create();
            }
            using (var stream = System.IO.File.Create(FilePath + "\\" + uploadRO.fileName)) {
                byte[] bytes = uploadRO.content;
                stream.Write(bytes, 0, uploadRO.content.Length);
                response.Data = new UploadPO() {
                    Edition = DateTime.Now.DayOfYear,
                    Revision = 0,
                    MinorVersion = 0,
                    OperativeFrom = DateTime.Now,
                    VersionFileSharePointPath = FilePath.Replace(@"\\", @"\"),
                    VersionFileName = uploadRO.fileName,
                    VersionFileSize = uploadRO.fileSize / 1024 / 1024,
                    VersionId = Guid.NewGuid(),
                };
            }
            response.StatusCode = HttpStatusCode.OK;
            return response;
        }
 public class UploadRO {
        public string uid { get; set; }
        public string fileName { get; set; }
        public int fileSize { get; set; }
        public byte[] content { get; set; }
    }
function onSaveRequest(
        files: UploadFileInfo[],
        options: { formData: FormData; requestOptions: any },
        onProgress: (uid: string, event: ProgressEvent<EventTarget>) => void
    ): Promise<{ uid: string }> {
        const currentFile = files[0] as UploadFileInfo;
        const uid = currentFile.uid;
        const saveRequestPromise = new Promise<{ uid: string }>( (resolve, reject) => {
            // as currently configured it is impossible to request a save from the UI if there are validation errors, but that can be changed so keeping this check in place
            if (currentFile.validationErrors && currentFile.validationErrors.length > 0) {
                reject({ uid: uid });
            } else {
                const reader = new FileReader();
                // onload is executed when the load even is fired i.e. when content read with readAsArrayBuffer, readAsBinaryString, readAsDataURL or readAsText is available
                reader.onload = () => {
                    if (reader.result && typeof reader.result === "string") {
                        // stripping the data-url declaration as per https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL
                        const base64Result = reader.result.split(",")[1];
                        // update viewModel and resolve
                        const fileUpload: IFileUploadViewModel = { uid: uid, fileName: currentFile.name, fileSize: currentFile.size!, content: base64Result};
                        Handler_Upload(fileUpload);
                        resolve({ uid: uid });
                    } else {
                        reject({ uid: uid });
                    }
                };
                // onprogress is fired periodically as the FileReader reads data and the ProgressEvent can be passed directly to the Upload control, handy!
                reader.onprogress = (data) => {
                    reader.readAsArrayBuffer(currentFile.getRawFile!())
                    console.log(data)
                    onProgress(uid, data);
                };
                // if the read is not completed due to error or user intervention, reject
                reader.onabort = () => {
                    reject({ uid: uid });
                };
                reader.onerror = () => {
                    reject({ uid: uid });
                };

               reader.readAsDataURL(currentFile.getRawFile!());
            }
        });

        return saveRequestPromise;
    }
const pageTable = (
        <div>
            <Upload 
                {...fileProps}
                batch={false}   
                multiple={false} 
                defaultFiles={[]}
                showFileList={true}
                restrictions={{
                    allowedExtensions: [".pdf"],
                }}
                withCredentials={true}
                onAdd={onAdd}
                onProgress={onProgress}
                onStatusChange={onStatusChange}
                onBeforeUpload={onBeforeUpload}
                onRemove={onRemove}
                saveUrl={onSaveRequest}
            />
        </div>
    )
    return <>{pageTable}</>

 

  beforeUpload(file, fileList) {
   var reader = new FileReader();
   const image = new Image();
   var height;
   var width;
   var base64Url;
   //因为读取文件需要时间,所以要在回调函数中使用读取的结果
   reader.readAsDataURL(file); //开始读取文件
   reader.onload = (e) => {
     image.src = reader.result;
     image.onload = () => {
       height = image.naturalHeight;
       width = image.naturalWidth;
       base64Url= e.target.result, //cropper的图片路径
     }
   }
   return false;
 }

 

posted @ 2022-04-19 12:42  Tammytan  阅读(88)  评论(0编辑  收藏  举报