且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 Java 中使用 Rest API 上传文件

更新时间:2022-03-17 00:37:26

我已经更新了下面类中的方法签名并且它工作正常.代替 @FormParam,使用 @FormDataParam("path") 字符串路径,它解决了我的问题.以下是更新后的代码:

I have updated signature of method in below class and its working fine. Instead of @FormParam, used @FormDataParam("path") String path and it solved my issue. Below is the updated code:

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import com.sun.jersey.core.header.FormDataContentDisposition;
import com.sun.jersey.multipart.FormDataParam;

@Path("/file")
public class UploadFileService {

@POST
@Path("/upload")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFile(
        @FormDataParam("file") InputStream uploadedInputStream,
        @FormDataParam("file") FormDataContentDisposition fileDetail,
        @FormDataParam("path") String path) {


    // Path format //10.217.14.97/Installables/uploaded/
    System.out.println("path::"+path);
    String uploadedFileLocation = path
            + fileDetail.getFileName();

    // save it
    writeToFile(uploadedInputStream, uploadedFileLocation);

    String output = "File uploaded to : " + uploadedFileLocation;

    return Response.status(200).entity(output).build();

}

// save uploaded file to new location
private void writeToFile(InputStream uploadedInputStream,
        String uploadedFileLocation) {

    try {
        OutputStream out = new FileOutputStream(new File(
                uploadedFileLocation));
        int read = 0;
        byte[] bytes = new byte[1024];

        out = new FileOutputStream(new File(uploadedFileLocation));
        while ((read = uploadedInputStream.read(bytes)) != -1) {
            out.write(bytes, 0, read);
        }
        out.flush();
        out.close();
    } catch (IOException e) {

        e.printStackTrace();
    }

   }

   }