Javaで画像をサーバーにアップロードする方法

HTMLフォームの構造

<div id="selectImage" align="right" style="width: 300px;font-size: 15px;">
    (形式: jpg, bmp, png, 100KB以内) 画像を選択
    <input type="text" id="imagePath" style="display: none;">
    <input type="file" id="fileInput" onchange="handleFileUpload(this, 100, 'previewImage', 'imagePath', 290, 190)" style="width: 70px;" class="easyui-linkbutton">
</div>
<br>
<div>
    <img id="previewImage" alt="">
</div>

画像アップロードのJavaScript関数

function handleFileUpload(inputElement, maxSizeInKB, imageDivId, pathInputId, width, height) {
    const file = inputElement.files[0];
    const reader = new FileReader();
    reader.readAsDataURL(file);
    let imageUrl = '';
    const pathInput = document.getElementById(pathInputId);
    const imageDiv = document.getElementById(imageDivId);
    const validExtensions = ['jpg', 'bmp', 'png'];

    try {
        if (file.size / 1024 > maxSizeInKB) {
            alert(`ファイルサイズが制限を超えています。${maxSizeInKB}KB未満にしてください`);
            pathInput.value = '';
            return;
        }

        const fileName = file.name;
        const fileExtension = fileName.substring(fileName.lastIndexOf('.') + 1).toLowerCase();
        if (!validExtensions.includes(fileExtension)) {
            alert('サポートされていないファイル形式です。jpg, bmp, pngのみ許可されています');
            pathInput.value = '';
            return;
        }
    } catch (error) {
        alert(`エラー: ${error.name}, ${error.message}`);
    }

    reader.onloadend = () => {
        imageUrl = reader.result;
        imageDiv.src = imageUrl;
        pathInput.value = file.name;
    };

    imageDiv.width = width;
    imageDiv.height = height;
    uploadFile(inputElement);
}

ファイルアップロード処理

function uploadFile(input) {
    const formData = new FormData();
    const file = input.files[0];
    const uploadUrl = getContextPathInfo() + '/LowZjblb/upload';

    if (file) {
        formData.append('file', file);
        $.ajax({
            url: uploadUrl,
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: response => {
                $('#storedImagePath').val(response.appenddata);
            }
        });
    }
}

Javaのコントローラーでの画像受信処理

@RequestMapping(value = "/upload", method = RequestMethod.POST)
@ResponseBody
@Log(module = "法証補領管理", operation = "追加")
public OperationResult receiveImage(@RequestParam("file") MultipartFile uploadedFile, HttpServletRequest request) {
    OperationResult result = new OperationResult(OperationResultTypeEnum.ERROR, "追加失敗");
    String directoryName = "UpFile";
    String originalFileName = uploadedFile.getOriginalFilename();
    String baseFileName = originalFileName.substring(0, originalFileName.lastIndexOf('.'));
    String savedFilePath = ImageUploader.storeFile(uploadedFile, baseFileName, directoryName, request);
    result.setResulttype(OperationResultTypeEnum.SUCCESS);
    result.setMsg("アップロード成功");
    result.setAppenddata(savedFilePath);
    return result;
}

画像保存のJavaメソッド

public static String storeFile(MultipartFile fileData, String fileNameWithoutExt, String dirName, HttpServletRequest request) {
    String rootPath = request.getSession().getServletContext().getRealPath("/");
    Calendar calendar = Calendar.getInstance();
    String year = String.valueOf(calendar.get(Calendar.YEAR));
    String month = String.valueOf(calendar.get(Calendar.MONTH) + 1);
    String targetDirectory = "UpFile/" + dirName + "/" + year + "/" + month + "/";

    File directory = new File(rootPath + targetDirectory);
    if (!directory.exists()) {
        directory.mkdirs();
    }

    String fileExtension = fileData.getOriginalFilename().substring(fileData.getOriginalFilename().lastIndexOf('.') + 1);
    String fullPath = targetDirectory + fileNameWithoutExt + "." + fileExtension;

    try (FileOutputStream outputStream = new FileOutputStream(rootPath + fullPath)) {
        outputStream.write(fileData.getBytes());
        return fullPath;
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

タグ: Java HTML javascript AJAX ファイルアップロード

10月12日 17:48 投稿