弘帝企业智能建站系统交流平台

 找回密码
 立即注册
查看: 275|回复: 1

【NET6】实现PUT方法上传FORM多图片和多参数

[复制链接]
发表于 2023-11-30 15:33:04 | 显示全部楼层 |阅读模式
此功能在Hondy.Demo.Modules中实现,经测试验证通过,完美解决415错误,400错误,Failed to read the request form. Multipart body length limit 16384 exceeded.等错误提示。
[html]
<form method="post" id="formDataForm" enctype="multipart/form-data">
    <div class="row mb-3">
        <div class="col-lg-2"><label for="title">Title:</label></div>
        <div class="col-lg-10">
            <input type="text" id="title" name="title" class="form-control" />
        </div>
    </div>
    <div class="row mb-3">
        <div class="col-lg-2"><label for="theme">Theme:</label></div>
        <div class="col-lg-10">
            <input type="text" id="theme" name="theme" class="form-control" />
        </div>
    </div>
    <div class="row mb-3">
        <div class="col-lg-2">
            <label for="html">HTML:</label>
        </div>        <div class="col-lg-10">
            <textarea id="html" name="html" rows="10" class="form-control"></textarea>
        </div>
    </div>
    <div class="row mb-3">
        <div class="col-lg-2">
            <label for="css">CSS:</label>
        </div>
        <div class="col-lg-10">
            <textarea id="css" name="css" rows="10" class="form-control"></textarea>
        </div>
    </div>
    <div class="row mb-3">
        <div class="col-lg-2">
            <label for="js">JS:</label>
        </div>
        <div class="col-lg-10">
            <textarea id="js" name="js" rows="10" class="form-control"></textarea>
        </div>
    </div>
    <div class="row mb-3">
        <div class="col-lg-2">
            <label for="images">Images:</label>
        </div>
        <div class="col-lg-10">
            <input id="images" name="images" type="file" class="form-control" multiple />
        </div>
    </div>
    <div class="row mb-3">
        <div class="col-lg-2">
            <label for="remark">Remark:</label>
        </div>
        <div class="col-lg-10">
            <textarea id="remark" name="remark" rows="10" class="form-control"></textarea>
        </div>
    </div>
    <div class="row">
        <div class="col-lg-2"></div>
        <div class="col-lg-10">
            <button type="submit" class="btn btn-primary me-3">Submit</button>
            <button type="reset" class="btn btn-primary">Reset</button>
        </div>
    </div>
</form>
<script src="~/js/modules.js"></script>

[JS]
document.getElementById('formDataForm').addEventListener('submit', function (e) {
    e.preventDefault();

    var formData = new FormData(document.getElementById('formDataForm'));
    var id = formData.get('id');
    var fileInput = document.getElementById('images');
    var file = fileInput.files[0];  // 获取文件输入框中选择的文件

    formData.append('file', file);  // 将文件数据添加到 FormData 对象中

    fetch('/controller/modules/' + id, {
        method: 'PUT',
        body: formData
    })
        .then(response => {
            if (response.ok) {
                // 提交成功后刷新表单列表
                alert("ok");
                loadFormDataList();
            }
            return response.json(); // 将响应解析为JSON
        })
        .then(data => {
            console.log(data);
        });
});

[NET6]
private async Task<string> UploadImageAsync(IFormFile image)
{
    string path = "uploadfiles/picture";
    var uploadPath = Path.Combine(RootPath, path);
    Console.WriteLine(uploadPath);
    if (!Directory.Exists(uploadPath))
    {
        Directory.CreateDirectory(uploadPath);
    }

    if (image != null && image.Length > 0 && image.ContentType.StartsWith("image/"))
    {
        var fileName = DateTime.Now.ToString("yyyyMMddHHmmssfff") + Path.GetExtension(image.FileName);
        string filePath = Path.Combine(uploadPath, fileName);

        // 限制图片大小不超过500KB
        if (image.Length <= 500 * 1024)
        {
            using (FileStream fs = new FileStream(filePath, FileMode.Create))
            {
                await image.CopyToAsync(fs);
            }
        }
        return $"{path}/{fileName}";
    }
    return "";
}

[HttpPut("{id}")]
public async Task<ActionResult> UpdateModules(int id, [FromForm] HD_Modules modules, IFormFileCollection images)
{
    Console.WriteLine("asdfasdf");
    string ImagePaths = "";
    Console.WriteLine(images.Count);
    List<string> imagePaths = new List<string>();
    if (images != null && images.Count > 0)
    {
        foreach (var file in images)
        {
            string imagePath = await UploadImageAsync(file);
            imagePaths.Add(imagePath);
        }
        ImagePaths = string.Join(",", imagePaths);
    }
    Console.WriteLine(imagePaths);
    Console.WriteLine(modules.Title);
    // 根据 ID 更新指定的表单数据
    string sql = "UPDATE HD_Module SET HD_Title=@Title,HD_Theme=@Theme,HD_Html=@Html,HD_CSS=@Css,HD_JS=@JS,HD_Remark=@Remark,HD_Images=@ImagePaths WHERE HD_ID=@ID";
    using (SqlCommand cmd = new SqlCommand(sql, connection))
    {
        cmd.Parameters.AddWithValue("@Title", modules.Title);
        cmd.Parameters.AddWithValue("@Theme", modules.Theme);
        cmd.Parameters.AddWithValue("@Html", modules.Html);
        cmd.Parameters.AddWithValue("@Js", modules.Js);
        cmd.Parameters.AddWithValue("@CSS", modules.Css);
        cmd.Parameters.AddWithValue("@Remark", modules.Remark);
        cmd.Parameters.AddWithValue("@ImagePaths", ImagePaths);
        cmd.Parameters.AddWithValue("@ID", id);
        try
        {
            int re = cmd.ExecuteNonQuery();
            connection.Close();
            connection.Dispose();
            if (re > 0)
            {
                return Ok();
            }
            else
            {
                return NotFound(); // 根据实际情况返回适当的状态码和错误信息
            }
        }
        catch (Exception ex)
        {
            // 处理异常,并返回适当的错误信息
            return StatusCode(500, ex.Message);
        }
    }
}

public class HD_Modules
{
    public int Id { get; set; }
    public string? Theme { get; set; }
    public string? Title { get; set; }
    public string? Html { get; set; }
    public string? Css { get; set; }
    public string? Js { get; set; }
    public string? Images { get; set; }
    public string? Remark { get; set; }
}

回复

使用道具 举报

 楼主| 发表于 2023-11-30 15:38:33 | 显示全部楼层

题外话

Failed to read the request form. Multipart body length limit 16384 exceeded.
当提示以上错误时,在Program.cs中找到builder定义项后面添加以下内容

builder.WebHost.ConfigureKestrel((context, options) =>
{
    //设置最大1G, 这里的单位是byte
    options.Limits.MaxRequestBodySize = null;
});


没有发现出错信息,但有没有解决字节限制,未经验证,仅供解决思路参考。
以上适用于Net6以上Program.cs脚本中。
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|Archiver|手机版|小黑屋|弘帝企业智能建站系统 ( 皖ICP备07503252号 )

GMT+8, 2024-4-28 17:16 , Processed in 0.109075 second(s), 15 queries .

Powered by Discuz! X3.4

© 2001-2017 Comsenz Inc.

快速回复 返回顶部 返回列表