|
實例
方式一:Nodejs
前端代碼:
<input type="file" name="" id="file">
<button onclick="doUpload()">上傳文件</button>
<img src="" alt="" id="img">
<script>
function doUpload(){
let file = $("#file").get(0).files[0]; // 獲取上傳文件的數據
// 將圖片轉換為 formData對象
let formdata = new FormData()
formdata.append("upload_name",file)
console.log("開始上傳~")
$.ajax({
url: "http://localhost:3000/upload",
type: "POST",
cache: false, // 不必須
data:formdata,
processData: false, // 必須
contentType: false,// 必須
success: function(data){
console.log(data);
if(data.err==0){
$("#img").attr("src",data.imgUrl);
}else{
alert("上傳失??!")
}
}
})
}
</script>
服務器代碼:
const express = require("express");
const request = require('request');
const path = require('path');
const multer = require("multer");
const app = express();
// 配置 multer:緩存
var storage = multer.diskStorage({
// 1. 設置上傳后文件的路徑,uploads文件夾會自動創(chuàng)建(最好手動建好)
destination:function (req,file,cb) {
cb(null,"./uploads")
},
// 2. 給上傳的文件重命名,獲取添加后綴名
filename:function (req,file,cb) {
// 前端上傳的文件名
let filename = req.body.filename;
var fileFormat = (file.originalname).split(".");
// 給圖片加上時間戳,可防止文件名字重復; fileFormat[fileFormat.length - 1]這里-1是取最后的后綴,因為'.'的個數多個
cb(null,file.fieldname '-' Date.now() '.' fileFormat[fileFormat.length - 1])
}
});
var upload = multer({
storage:storage
});
// 接口:上傳圖片必須使用post方法
// uploads.single("name") 里面是上傳圖片的key值,這個必須和前端統(tǒng)一,不然上次不成功
app.post("/upload",upload.single("upload_name"),(req,res)=>{
console.log(req.file);
// 前端上傳的文件名
let filename = req.body.filename;
let {size,mimetype,path} = req.file;
let types = ['jpg','jpeg','png','gif']; // 允許上傳的文件類型
let tmpType = mimetype.split("/")[1];
if(size>500000){
return res.send({err:-1,msg:"文件太大"});
}else if(types.indexOf(tmpType)==-1){
return res.send({err:-2,msg:"媒體類型錯誤"});
}else{
let url = `/upload/${req.file.filename}`
res.send({err:0,imgUrl:url});
}
});
// 開啟服務器
app.listen(3000,function (request,response) {
console.log("服務器啟動~~~");
});
// 開放靜態(tài)目錄(上傳圖片保存的位置,可以url訪問)
let upload_path = path.join(__dirname,"./uploads"); // 實現路徑拼接
app.use("/upload",express.static(upload_path));
方式二:Javaweb
前端代碼:
<script>
var reader = new FileReader();
reader.readAsDataURL(document.getElementById("product-img-input").files.item(0));
reader.onload = function () {
var productImgBase64 = this.result;
$.ajax({
url: "/ProductAdd",
type: "POST",
dataType: 'json',
data: {"productImg": productImgBase64},
success: function (response) {
console.log("上傳成功");
},
});
};
</script>
服務器接收:
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import java.io.*;
public class Base64Utils {
// 函數1:將數據data轉成png存到src/image下命名位id.png
public static void saveBase64DataToPng(String data, int id) {
try {
BASE64Decoder decoder = new BASE64Decoder();
String path = Base64Utils.class.getResource("").getPath().split("out/")[0] "src/images/" id ".png";
FileOutputStream write = new FileOutputStream(new File(path));
byte[] decoderBytes = decoder.decodeBuffer(data.split(",")[1]);
write.write(decoderBytes);
write.close();
} catch (Exception e) {
e.printStackTrace();
}
}
// 函數2:根據id找到id.png的圖片轉成base64返回
public static String PngToBase64(int id) {
InputStream in = null;
byte[] data = null;
String path = Base64Utils.class.getResource("").getPath().split("out/")[0] "src/images/" id ".png";
try {
in = new FileInputStream(path);
data = new byte[in.available()];
in.read(data);
in.close();
} catch (Exception e) {
e.printStackTrace();
}
BASE64Encoder encoder = new BASE64Encoder();
return "data:image/png;base64," encoder.encode(data).replace("\r\n","");
}
}
方式三:Javaweb
package util;
import com.alibaba.fastjson.JSON;
import model.Result;
import model.Upload_Result;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;
@WebServlet(name = "uploadPicture", urlPatterns = "/uploadPicture")
public class uploadPicture extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
System.out.println("接收圖片----");
if(!ServletFileUpload.isMultipartContent(request)){
throw new RuntimeException("當前文件不支持文件上產");
}
System.out.println("接收圖片完成----");
String path = request.getSession().getServletContext().getRealPath("/upload");
System.out.println(path);
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setRepository(new File(path));
factory.setSizeThreshold(1024 * 1024);
ServletFileUpload upload = new ServletFileUpload(factory);
System.out.println(upload);
List<FileItem> items=null;
try {
System.out.println("000000000000----");
items = upload.parseRequest(request);
System.out.println("大?。? items.size());
} catch (FileUploadException e) {
e.printStackTrace();
}
Iterator iter = items.iterator();
String picPath = "";
while (iter.hasNext()) {
System.out.println("111111111111111111111");
FileItem item = (FileItem) iter.next();
if (!item.isFormField()) {
// 根據時間戳創(chuàng)建頭像文件
String filename = System.currentTimeMillis() ".jpg";
System.out.println(request.getContextPath());
//項目下創(chuàng)建文件夾
File f = new File(getServletContext().getRealPath("upload"));
// D盤的存放文件夾
// File f = new File("D://javaWebUploadFile");
if (!f.exists()) {
f.mkdir();
}
String imgsrc = f "/" filename;
System.out.println(imgsrc);
// /reports/1551435783395.jpg
picPath = "/upload/" filename;
// 復制文件
InputStream is = item.getInputStream();
FileOutputStream fos = new FileOutputStream(imgsrc);
byte b[] = new byte[1024 * 1024];
int length = 0;
while (-1 != (length = is.read(b))) {
fos.write(b, 0, length);
}
fos.flush();
fos.close();
} else {
System.out.println(item.getFieldName());
String value = item.getString();
value = new String(value.getBytes("ISO-8859-1"), "UTF-8");
System.out.println(value);
}
}
ArrayList<Object> lst=new ArrayList<>();
Upload_Result result_data=new Upload_Result();
result_data.setFile(picPath);
lst.add(result_data);
Result result=new Result();
result.setCode(0);
result.setMsg("請求成功");
result.setCount(10);
result.setData(lst);
String content= JSON.toJSONString(result);
// 3.發(fā)送數據
response.setCharacterEncoding("UTF-8");
//通知瀏覽器使用utf-8解碼
response.setHeader("Content-type", "text/html;charset=utf-8");
PrintWriter out = response.getWriter();
out.write(content);
}
}
四、Django

網頁表單端加上enctype=“multipart/form-data”
注意:setting.py配置
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
STATICFILES_DIRS=(
os.path.join(BASE_DIR, 'media'),
os.path.join(BASE_DIR,"static"),
)
前端:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>上傳圖片</title>
</head>
<body>
<form action="/upload/" method="POST" enctype="multipart/form-data">
<input type="file" name="imgFile"><br/><br/>
<input type="submit" value="上傳">
</form>
</body>
</html>
后端:
from django.urls import path
from django.shortcuts import render,redirect,HttpResponse
from uploadImg import settings
def get_uploadHtml(request):
if request.method=="GET":
print("獲取上傳界面~")
return render(request,"upload.html")
def upload_imgFile(request):
if request.method=="POST":
print("前端上傳圖片")
# 1. 接收圖片
imageFile = request.FILES["imgFile"]
print(imageFile)
# 2. 驗證圖片
contentTypes = ['image/jpeg', 'image/png', 'image/gif','image/bmp']
if imageFile.content_type not in contentTypes:
return HttpResponse('圖書格式錯誤', '請上傳圖片格式')
# 3. 保存圖片
# save_path = '%s%s%s' % (settings.BASE_DIR,settings.MEDIA_URL, imageFile.name) # 絕對路徑保存
save_path = 'static/' imageFile.name # 相對路徑保存
print("save_path:",save_path)
with open(save_path, 'wb ') as f:
f.write(imageFile.read())
return HttpResponse("上傳成功,可訪問:" "http://127.0.0.1:8000/" save_path)
urlpatterns = [
path('gethtml/', get_uploadHtml),
path('upload/', upload_imgFile),
]
訪問靜態(tài)目錄:
注意:setting.py配置 下面配置是添加了兩個文件夾作為靜態(tài)目錄,但是訪問時,都是http://localhost:8000/static/***,都是static開始噢 ?。?!然后才是文件名。
STATIC_URL = '/static/'
STATICFILES_DIRS=(
os.path.join(BASE_DIR, 'media'),
os.path.join(BASE_DIR,"static"),
)
  
來源:https://www./content-1-868601.html
|