html 保存文件指定路径,78.上传文件及在服务器保存文件到任意路径

上传文件到服务器是一个常用的操作,而在服务器上保存文件就需要多多用心了。因为你不可能只在一个路径里保存文件,所以需要实践一下保存文件到任意位置。当然,前提是你的应用程序有这样的操作权限。

首先建立一个main.go文件,作为项目的起点。并使用一个网页模板JoelUploadFile.html,作为操作界面。

c045c04d2210

代码目录结构

在main文件中,准备好页面路径、上传路径、文件访问路径等,及相对应函数

/**

* CofoxS

* @Author: Jian Junbo

* @Email: junbojian@qq.com

* @Create: 2019/3/30 22:25

* Copyright (c) 2019 Jian Junbo All rights reserved.

*

* Description:

*/

package main

import (

"fmt"

"goHttps/uilFileSys"

"html/template"

"log"

"net/http"

)

func main() {

fmt.Println("Hello Moon!")

log.Println("随意指定文件保存路径!")

//--页面路径

http.HandleFunc("/", IndexHandler)

//--上传文件

http.HandleFunc("/fileSys/tmpUpload/", uilFileSys.FileTmpUpload)

//----上传文件

http.Handle("/tmpfiles/", http.StripPrefix("/tmpfiles/", http.FileServer(http.Dir("tmp"))))

websitename := ":90"

http.ListenAndServe(websitename, nil)

}

func IndexHandler(writer http.ResponseWriter, request *http.Request) {

//取消获取facicon.ico的访问

if request.RequestURI == "/facicon.ico" {

return

}

//---------绑定模板页 begin-------------

t, err := template.ParseFiles("./templatefile/JoelUploadFile.html")

if err != nil {

fmt.Println("发生了错误!")

fmt.Fprintln(writer, err)

}

t.ExecuteTemplate(writer, "JoelUploadFile.html", "")

//---------绑定模板页 end---------------

}

需要绑定的模板文件 JoelUploadFile.html

企业上传文件

input{

line-height: 20px;

padding-left: 2px;

padding-right: 2px;

margin-left: 2px;

margin-right: 2px;

background-color: #eaf4fc;

border-color: #b5c1e4;

border-width: 1px;

border-style: solid;

border-radius: 3px;

}

/*上传文件*/

.file {

position: relative;

display: inline-block;

background: #D0EEFF;

border: 1px solid #99D3F5;

border-radius: 4px;

padding: 4px 12px;

overflow: hidden;

color: #1E88C7;

text-decoration: none;

text-indent: 0;

line-height: 20px;

}

.file input {

position: absolute;

font-size: 100px;

right: 0;

top: 0;

opacity: 0;

}

.file:hover {

background: #AADFFD;

border-color: #78C3F3;

color: #004974;

text-decoration: none;

}

/*同步数据*/

function synkFile(srcObj, showObj, newObj) {

var srcO = document.getElementById(srcObj);

var showO = document.getElementById(showObj);

var new0 = document.getElementById(newObj);

/*if (srcO.value.length > 0) {

showO.value = srcO.value;

}

*/

// showO.value = "";

new0.innerText = "";

for (var i = 0; i < srcO.files.length; i++) {

// showO.value += srcO.files[i].name + "|";

new0.innerText += srcO.files[i].name + "|\r\n";

}

}

/*保存修改数据*/

function saveF() {

var frm = document.getElementById("formSave");

var u_id = document.getElementById("u_Id");

if (u_id.value.length <= 0) {

alert('\'流水号\'丢失!');

return;

}

frm.submit();

}

企业上传文件,按照“平台》企业编号》系统》年月日”来储存文件,文件名使用生成时间

实现上传功能的函数

/**

* CofoxS

* @Author: Jian Junbo

* @Email: junbojian@qq.com

* @Create: 2019/3/31 23:27

* Copyright (c) 2019 Jian Junbo All rights reserved.

*

* Description: 企业文件管理

*/

package uilFileSys

import (

"cofoxWebPlatform/platform/lib"

"cofoxWebPlatform/platform/model"

"encoding/json"

"fmt"

"io"

"net/http"

"os"

"path"

)

//上传文件到临时文件路径,前提条件是当前用户是在线用户

func FileTmpUpload(writer http.ResponseWriter, request *http.Request) {

//接收数据

keyId := request.FormValue("keyId") //key身份Id

//get a ref to the parsed multipart form

m := request.MultipartForm

//get the *fileheaders

files := m.File["uploadfile"]

for i,_ := range files {

//save the file as filename

filename := lib.JoelGetNowFullTimeNumber() + path.Ext(files[i].Filename)

//for each fileheader, get a handle to the actual file

file, err := files[i].Open()

defer file.Close()

if err != nil {

http.Error(writer, err.Error(), http.StatusInternalServerError)

return

}

//create destination file making sure the path is writeable.

dst, err := os.Create("./tmp/" + filename)

defer dst.Close()

if err != nil {

http.Error(writer, err.Error(), http.StatusInternalServerError)

return

}

//copy the uploaded file to the destination file

if _, err := io.Copy(dst, file); err != nil {

http.Error(writer, err.Error(), http.StatusInternalServerError)

return

}

tmpfile := dst.Name() // 写入保存文件的位置和文件名

lib.JoelLog(keyId,tmpfile) //服务端输出

resultValue := model.JoelBaseAskResultNormal{}

resultValue.AskResult = tmpfile

back,_ := json.Marshal(resultValue)

fmt.Fprint(writer,string(back)) //返回客端数据

}

}

运行此程序

c045c04d2210

服务器显示

c045c04d2210

浏览器显示

点击“上传附件”,选择要上传的文件。

c045c04d2210

选择一个图片文件

点击“保存”按钮,激发js的saveF()函数,提交form到服务器

c045c04d2210

一般都会顺带提交一些其他数据,例如:u_Id

提交后,文件保存到 "/tmp/" 路径,这个路径在当前程序的根上。

c045c04d2210

已上传到服务器的文件

c045c04d2210

服务器返回的json串

下面可以指定保存的其他路径

当前文件保存的位置是 tmp 路径,是在 \uilFileSys\EntFileMS.go 中定义的

//create destination file making sure the path is writeable.

dst, err := os.Create("./tmp/" + filename)

用windows系统来举例,如果我希望文件保存在另一个位置,比如:e盘,这行代码只需要修改为

//create destination file making sure the path is writeable.

dst, err := os.Create("e://" + filename)

如果,你上传之后,还想能够通过浏览器访问到这个文件,那么在 main.go 中,有这样的一行代码

//----上传文件

http.Handle("/tmpfiles/", http.StripPrefix("/tmpfiles/", http.FileServer(http.Dir("tmp"))))

你需要把它改成

//----上传文件

http.Handle("/tmpfiles/", http.StripPrefix("/tmpfiles/", http.FileServer(http.Dir("e:\\"))))

至此,大功告成!你已经可以把文件上传到 e 盘了。

在此基础上,你应该可以动态的指定每次上传文件的物理路径了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java可以通过使用标准的Java IO API和网络编程API从服务器上下载文件。以下是一些基本步骤: 1. 创建一个URL对象,使用该对象表示服务器上的文件路径文件名。 2. 使用URLConnection打开连接并设置HTTP请求的相关属性(例如,使用GET请求方法)。 3. 使用URLConnection.getInputStream()方法获取输入流,这个流可以用于读取服务器上的文件内容。 4. 将输入流写入到程序中,可以使用Java IO API中的文件输出流或其他适当的输出流。 下面是一些示例代码,可以根据您的需要进行修改: ```java import java.io.*; import java.net.*; public class FileDownloader { public static void main(String[] args) { String serverFilePath = "http://example.com/path/to/file.jpg"; // 服务器文件路径 String localFilePath = "/path/to/local/file.jpg"; // 下载到本地的文件路径 try { URL url = new URL(serverFilePath); URLConnection connection = url.openConnection(); InputStream inputStream = connection.getInputStream(); OutputStream outputStream = new FileOutputStream(localFilePath); byte[] buffer = new byte[4096]; int bytesRead = -1; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } outputStream.close(); inputStream.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } ``` 在上面的示例中,我们首先创建一个URL对象来表示服务器文件路径,然后打开URLConnection并获取输入流。接下来,我们使用Java IO API中的FileOutputStream将输入流写入到本地文件中。 请注意,如果服务器需要进行身份验证或使用HTTPS协议,您可能需要在打开URLConnection之前设置其他HTTP请求属性。具体的细节可能会因服务器的配置而有所不同。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值